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 one of the switches
- ●Consistency maintenance: keeping parallel switches in sync requires manual discipline
- ●Change amplification: each new type requires modifying several files instead of one
Estimated Annual Cost
Cost of one instance a year by team size, from our model at $180K fully-loaded cost per engineer. Low and high use the bottom and top of the Medium inputs; mid is halfway. See full methodology.
| Team Size | Low | Mid | High |
|---|---|---|---|
| 3 devs | $2K | $4K | $5K |
| 5 devs | $3K | $5K | $8K |
| 8 devs | $4K | $8K | $12K |
| 10 devs | $5K | $10K | $15K |
| 20 devs | $9K | $19K | $28K |
These are model outputs, not measurements. Every input is on the cost model page, and the same model produces the figures on the 22 smells page. Put in your own team and cost in the smell profile calculator.
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