Refactoring Form Template Method
ProblemYour subclasses implement algorithms that contain similar steps in the same order.
SolutionMove the algorithm structure and identical steps to a superclass, and leave implementation of the different steps in the subclasses.
Subclasses are developed in parallel, sometimes by different people, which leads to code duplication, errors, and difficulties in code maintenance, since each change must be made in all subclasses.
Code duplication does not always refer to cases of simple copy/paste. Often duplication occurs at a higher level, such as when you have a method for sorting numbers and a method for sorting object collections that are differentiated only by the comparison of elements. Creating a template method eliminates this duplication by merging the shared algorithm steps in a superclass and leaving just the differences in the subclasses.
Forming a template method is an example of the Open/Closed Principle in action. When a new algorithm version appears, you need only to create a new subclass; no changes to existing code are required.
How to Refactor
Split algorithms in the subclasses into their constituent parts described in separate methods. Extract Method can help with this.
The resulting methods that are identical for all subclasses can be moved to a superclass via Pull Up Method.
The non-similar methods can be given consistent names via Rename Method.
Move the signatures of non-similar methods to a superclass as abstract ones by using Pull Up Method. Leave their implementations in the subclasses.
And finally, pull up the main method of the algorithm to the superclass. Now it should work with the method steps described in the superclass, both real and abstract.
Tired of reading?
No wonder, there are 7 hours worth of the text on this website.
Try out something different. We've just launched the interactive learning course on refactoring. It has more content and much more fun than a boring text.Learn more...
Everything is quite simple. This example is like video (but much cooler):
- After pressing the Play button, you will see floating messages, which will guide you through the example. You can proceed by clicking on them.
- You can fast-forward or return to previous steps by pressing arrow buttons on the left.
- Also, you can take a look at the code diff window, which will show what has changed in code during the example ()
- To check the code for errors, you can press "Compile and test" button ()