Replace Conditional with Polymorphism
Move each leg of the conditional to an overriding method in a subclass.
“You have a conditional that chooses different behavior depending on the type of an object.”
OO Style.
graph LR
A[Switch Statement] -->|Refactoring| B[Polymorphic Classes]
When to apply (Smells)
- Switch Statements: Switching on type code.
- Refused Bequest: Subclasses inheriting stuff they arguably shouldn’t because of shared switch logic? (Less direct link).
Motivation
- Extensibility: Add a new type without modifying the switch statement (OCP).
Mechanics (Steps)
- Create subclasses for each type (if not existing).
- Move the logic from the conditional branch to the subclass method.
- Replace the conditional with a call to the polymorphic method.
Explanation
Problem
switch (bird.type) { case EUROPEAN: ... case AFRICAN: ... }
Solution
bird.getSpeed() (where EuropeanBird and AfricanBird implement getSpeed).
Pros and Cons
| Pros | Cons |
|---|---|
Code example
Typescript
Before
After
PHP
Before
After