Also known as

Refactoring Form Template Method


Your subclasses implement algorithms that contain similar steps in the same order.


Move the algorithm structure and identical steps to a superclass, and leave implementation of the different steps in the subclasses.
Form Template Method - Before
Form Template Method - After

Why Refactor

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

  1. Split algorithms in the subclasses into their constituent parts described in separate methods. Extract Method can help with this.

  2. The resulting methods that are identical for all subclasses can be moved to a superclass via Pull Up Method.

  3. The non-similar methods can be given consistent names via Rename Method.

  4. Move the signatures of non-similar methods to a superclass as abstract ones by using Pull Up Method. Leave their implementations in the subclasses.

  5. 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...

Live Example

First time here? No worries!

Everything is quite simple. This example is like video (but much cooler):

  1. After pressing the Play button, you will see floating messages, which will guide you through the example. You can proceed by clicking on them.
  2. You can fast-forward or return to previous steps by pressing arrow buttons on the left.
  3. Also, you can take a look at the code diff window, which will show what has changed in code during the example ()
  4. To check the code for errors, you can press "Compile and test" button ()