Switch Statements

Using switch/case instead of polymorphism.

“Most people understand that you shouldn’t use a switch statement… but few realize just how bad it is.” – Fowler & Beck

Signs of Use (Symptoms)

  • switch on a “type” field (if (animal.type === 'DOG') ... else if (animal.type === 'CAT')).
  • The same switch appears in multiple methods/files.

Why it is bad (Consequences)

  • Open/Closed Violation: Adding a new type requires modifying existing switch statements everywhere.
  • Duplication: Same logic repeated.

Why it happens (Root Cause)

It’s the procedural way from C. Developers unfamiliar with polymorphism default to switch.

When it might be okay (Exceptions)

  • Simple factory methods.
  • Parsing commands or event types where the structure is unlikely to change.

Explanation

Problem

You have a type field. You switch on it to determine behavior.

The Flaw

Every new type requires editing the switch. Easy to miss a case.

Real world analogy

A receptionist who asks “What is your complaint?” then reads from a manual for every possible answer, versus routing you to a specialist who already knows.

Refactoring Solution

  • Replace Conditional with Polymorphism: Create subclasses or use Strategy.

Pros and Cons (of the Antipattern)

Pros (Why people do it) Cons (The price you pay)
  • All logic in one place
  • OCP violation
  • Duplication across switches
  • Comparison

    • Related Antipatterns: Type Code.
    • Related Principles: Violates OCP, Polymorphism.

    Code example

    Typescript

    Bad (The Antipattern)

    Good (The Fix)

    PHP

    Good (The Fix)