You have a method that does not simplify well with the composed method pattern. Local variables are so intertwined that you cannot extract methods. How do you refactor a method where many lines of code share many arguments and temporary variables, that are hard to isolate from each other?
Some methods are too complicated, where different parts of the code need access to common variables. If you apply composed method and extract parts of code to different methods, it only worsens the problem. Since all parts of such a method generally need all the temporary variables and parameters, any piece of method you break off requires six or eight parameters. In these situations, we can apply the method object pattern.
Method Object Pattern
- Transform the method into a separate class so that the local variables become fields of the class. Ideally, the name of this class relates to a verb, e.g. Processor, Executor, etc.
- Then you can split the method into several methods within the same class.
- Replace the body of the original method in the original class by creating a method object and calling its executor method.
- Isolating a long method in its own class prevents a method from ballooning in size.
- This also allows splitting it into methods on the new class, which have shared access to the class instance variables.
- You have to add a new class, which might add to the complexity.
- If the method you are trying to refactor is not hard to understand and the code is not duplicated, even though it’s big, leave it.