1

I currently have a long function that essentially carries out multiple different tasks sequentially (eg. it first clones a git repository, then edits some file in that repository, creates a new branch etc). What would be a clean way to refactor this code to a design pattern? I was thinking of creating a separate class for each sub class, and then chain these tasks together, but I am not sure if this is the best way of doing it. After reading more on the Chain of responsibility pattern, its principle is different to what i am trying to accomplish. My codebase is using python

Ideal outcome ->

MainClass calls classes
TaskA
TaskB
TaskC

thecoder
  • 43
  • 4

2 Answers2

1

Chain of responsibility pattern is used when you want to handle some request. As refactoring.guru says:

Chain of Responsibility is a behavioral design pattern that lets you pass requests along a chain of handlers. Upon receiving a request, each handler decides either to process the request or to pass it to the next handler in the chain.

However, you want to execute multiple different tasks sequentially. So it is not the case where Chain of responsibility pattern can be used.

I thought that Template method pattern can be used here, however it is not necessary to override behavior of specific steps.

So it looks like we can avoid to use any pattern and your idea is perfectly suitable for you:

MainClass calls classes
TaskA
TaskB
TaskC

I would suggest to apply SOLID principles here. E.g., you want to:

  • clone a git repository
  • edit some file in that repository
  • creates a new branch.

So it looks like the following class can be created:

public class Git
{
    public void CloneRepository() { }

    public void CreateNewBranch() { }

    public void AddTo() { }
}

And then the following methods can be created:

CloneRepository();
EditFile();
CreateNewBranch();
StepUp
  • 36,391
  • 15
  • 88
  • 148
0

Look at moving each task into a 'service' class, which you pass into the constructor of your MainClass and call when needed.

Or just move each task into a private method within the main class to keep things neater.

Look up SOLID design of you haven't already - this would fall under 'single responsibility'.

george7378
  • 135
  • 2
  • 10