How to refactor method which performs multiple steps (dependent on each other)?
What is the best way to refactor a method which has many steps in it? For example, a m开发者_运维百科ethod 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
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.
Builder Pattern is the appropriate pattern.
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.
精彩评论