Card 04/ 09
All 9 cards
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.
| Compared on | if / else if | switch |
|---|---|---|
| Tests | A condition per rung | One value against constants |
| Accepts | Anything that produces a boolean | int, char, String, enum, and sealed types |
| Ranges | Natural | Only by listing every value |
| Many values, one outcome | A long || chain | Comma-separated on one case |
| Exhaustiveness | Nothing checks it | Checked 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.