views:

73

answers:

3

What is the best way to refactor a method which has many steps in it? For example, a method which setups some objects, creates several objects (Eg a database table), and so on - basically, one method which does a set of related steps.

Would this be best suited to the command design pattern?

Thanks

+2  A: 

Builder Pattern is the appropriate pattern.

fuzzy lollipop
+3  A: 

Well, there is no general answer to that. But about your example of creating and setting up objects, look into the Builder Pattern and the Factory Patten. The command pattern is useful when you have different possible actions (e.g. messages passed through a queue).

Sometimes it is also good for the readability of your code to just look for semantic units in your method and refactor them into methods, even when you do not reuse them elsewhere. A call to NotifyAllClients tells a reader more than a loop over some collection that calls some method.

Space_C0wb0y
Indeed, what Eric said. Why the downvote?
Space_C0wb0y
I downvoted an incorrect one liner; seems you fixed it soI changed my vote.
Pierreten
@Pierreten: Though not required by any means, you might want to consider leaving a comment when you downvote to help improve the overall quality of SO. http://meta.stackoverflow.com/questions/135/encouraging-people-to-explain-down-votes
Eric J.
A: 

Other ways of refactoring than the already mentioned ones could be using Template Method design pattern to allow to extract different parts and probably exchange them if needed in future. You could as well use even the State pattern, when you would like to rearrange those different parts of the method.

Gabriel Ščerbák