Initial Situation

Two methods perform similar steps, yet steps differ slightly.

Goal

Create a generalized method (the Template method) in a parent class and provide specific extension points for overriding.

Improves

Duplicated Code   

Difficulty

easy

Pros/Cons

Removes duplicate code from sub-classes.
Helps communicate the different steps of an algorithm.
Provides explicit extension points for sub-classes.
Makes code more complex if the similarity in both methods is low.
Setup Continuous Code Quality Management in minutes.

Refactoring Basics

Create Template Method

Overview

The template method refactoring can be applied easily to reduce duplicate code in algorithms. Instead of allowing sub-classes to override the entire logic of a method, the parent class provides specific extension points for sub-classes.

This refactoring should be used if you want to make sure that essential parts of an algorithm are followed while still allowing certain parts of the algorithm to be changed.

The Template Method Pattern (uses inheritance) is very similar to the Strategy pattern (uses composition) as such the benefits of either pattern closely relate to these fundamental code design approaches. Generally, the Strategy pattern allows you to make more fine-grained replacements of the algorithm in contrast to using a sub-class.

Further Resources

Checklist

Step 1
Find two methods in sub-classes which perform similar steps
Find two methods and extract the parts of each method which differ in both methods into new methods.
Step 2
Unify the names of the now identical methods
Unify the names of the methods which are now identical.
Step 3
Consolidate method in the parent class
Move one of the identical methods to the parent class and remove the other one from the sub-class.
Step 4
Create abstract methods in the parent class
Create abstract methods in the parent class for each of the different methods in sub-classes.

How to use the Checklist?

Checklists present a proven order of necessary refactoring steps and are especially helpful for beginners.

If you feel comfortable with a refactoring, there is no need to follow each of the steps literally; you can often perform multiple steps at once or skip some.

We suggest to try the recommended order at least once; this will often provide new insights - even for seasoned developers.