Switch Statements: What It Costs and How to Fix It
Complex switch/case or if/else chains that duplicate type-checking logic across multiple locations.
What It Is
The Switch Statements smell occurs when the same conditional logic (switch/case or long if/else chains) checking the same type or status code appears in multiple places throughout the codebase. A single switch statement is fine. The smell arises when adding a new case requires updating switches scattered across 5 different files. This is a violation of the Open/Closed Principle: the code is not open for extension without modification.
Why It Costs Money
Adding a new case requires finding and updating every switch on that type. In large codebases, developers regularly miss 1-2 locations, causing bugs that only manifest for the new case and are difficult to reproduce.
Each duplicated switch is a maintenance burden. When business rules for a case change, every switch must be updated consistently. Inconsistency between switches creates subtle behaviour differences.
Type-checking switches resist automated detection because they look different in each location (some use switch, some use if/else, some use ternary operators).
Specific Cost Mechanisms
- ●Missed-case bugs: adding a new type and missing 1-2 switches costs 4-8 hours per incident
- ●Consistency maintenance: keeping 5-10 parallel switches in sync requires manual discipline
- ●Change amplification: each new type requires modifying 5-10 files instead of 1
Estimated Annual Cost
Cost per instance by team size and codebase size. Based on $120,000 average developer salary. See full methodology.
| Team Size | Small (<50k LOC) | Medium (50k-200k) | Large (200k+) |
|---|---|---|---|
| 3 devs | $1,500 | $3,600 | $7,200 |
| 5 devs | $2,500 | $6,000 | $12,000 |
| 10 devs | $3,750 | $9,000 | $12,000 |
| 20 devs | $5,000 | $12,000 | $12,000 |
How to Detect It
Specific rules and thresholds for automated detection. See full tool comparison.
Excessive switch cases, missing default clause
Switch statements inflate cognitive complexity score
Cyclomatic complexity catches complex switches
Density metric identifies overloaded switches
Refactoring Patterns
Proven techniques to eliminate this smell. See all refactoring patterns.
Replace Conditional with Polymorphism
The same type check appears in 3+ locations
Replace Type Code with State/Strategy
Behaviour varies by a type code or status field
Introduce Null Object
One case in the switch handles a null or missing value