Card 04/ 09

ComparisonDifficulty: Intermediate1 min

When to Reach for switch and When for else if

Both shapes will do either job, badly. A switch forced to express a range turns into a case per value; an if ladder forced to express a lookup turns into twenty rungs that all compare the same variable.

The two branching shapes on what they test, what they accept and what they cost
Compared onif / else ifswitch
TestsA condition per rungOne value against constants
AcceptsAnything that produces a booleanint, char, String, enum, and sealed types
RangesNaturalOnly by listing every value
Many values, one outcomeA long || chainComma-separated on one case
ExhaustivenessNothing checks itChecked by the compiler over an enum or sealed type

The decision rule. Ask what the branches are testing. If every rung compares the same variable to a constant, it is a switch. If the rungs test different things, or the same thing with > and <, it is an if ladder.

The exhaustiveness row is the one that earns its place in real code. A switch over an enum with no default fails to compile the day somebody adds a constant, which turns a silent wrong answer into a build error. An if ladder over the same enum quietly falls through to its else forever.