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)

  1. Create subclasses for each type (if not existing).
  2. Move the logic from the conditional branch to the subclass method.
  3. 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
  • OCP compliant
  • Removes switch statements
  • More classes
  • Code example

    Typescript

    Before

    After

    PHP

    Before

    After