Replace Conditional Logic with Strategy

This is one of the refactorings in Joshua Kerievsky’s book. This recipe is for the initial steps before the refactoring “Conditional to Polymorphism.”

Examine

Usually the prompt for this refactoring is unnecessary conditional complexity with deep nesting. In particular, when the program is changing behaviour based on a type code or a particular fixed set of conditions. If the class currently containing this behaviour is plausibly going to become the superclass in the Strategy pattern, then you could just extract a method and then go directly to “Conditional to Polymorphism.”

Prepare

Implement

Clear

Check the names of the new method and class make sense. Check all the parameters to the new method make sense. Some of them might want to become constructor arguments, or you might want to move additional methods to this class.

Follow up

Use ‘Replace Conditional with Polymorphism’ to make the concrete strategy classes.

Prompted by Code Smells

Relevant Learning Hours

Sources

Back to All Refactorings