Replace Conditional with Polymorphism

This refactoring replaces conditional logic with classes and polymorphism. The code smell that leads you to it is having a lot of similar switch statements that switch on type.

Examine

Identify all the places with a repeated switch statement, that switch on the same type and have similar cases.

Prepare

All these switches should be in functions on the same class - the one which “has” the type that is being switched on. Extract methods as needed and move them to the class which will become the base of the polymorphic hierarchy.

If the constructor to the class is called in a lot of places it’s probably worth first doing ‘replace constructor with factory method’.

Implement

Clear

Consider whether the superclass should be an interface or an abstract class.

Prompted by Code Smells

Relevant Learning Hours

Sources

Back to All Refactorings