Switch Statements

November 25, 20269 minutes

One new device, three silent bugs. Learn why the smell is the same switch repeated, how to replace it with a class per kind, and when an exhaustive switch is the right answer.

You add one new device to a smart home app: a front door camera. It compiles, and the tests pass. Then the dashboard shows a question mark for its icon, the energy report says it uses nothing, and tapping it does nothing at all. Three features broke, and nobody touched their code. The answer is a smell called Switch Statements, and it isn’t quite what the name suggests.

Prefer to watch? The narrated video covers the same lesson (about 8 minutes). The article follows it section by section, with diagrams and a little extra depth.

One new device, three silent bugs

The camera shows “?”, “0 W” and a tap that does nothing. Where did the camera go wrong? Not in the dashboard, the energy report or the tap handler: none of them changed. Keep the question in mind.

The rulebook

Picture a board game’s rulebook, arranged by topic. There’s a chapter on moving, a chapter on attacking, and a chapter on healing, and each chapter lists every piece: the knight, the archer and the healer.

Then an expansion adds a dragon. Every chapter needs a new entry. The printer adds two of them, and misses the third. So how does the dragon attack? Nobody knows, so the players fall back on a basic attack.

That rulebook is our app. The chapters are icon, watts and onTap. The pieces are LIGHT, THERMOSTAT and LOCK. And the basic attack is the default branch. The device kind is a type code: a value that the code keeps switching on.

The rulebook mapped onto code. Chapters by topic (moving, attacking, healing) are operations (icon, watts, onTap); pieces are device kinds; an expansion piece is the new CAMERA kind; the missed chapter entry is a switch nobody updated; the basic attack fallback is the default branch. The rulebook mapped onto code. Chapters by topic (moving, attacking, healing) are operations (icon, watts, onTap); pieces are device kinds; an expansion piece is the new CAMERA kind; the missed chapter entry is a switch nobody updated; the basic attack fallback is the default branch.
The rulebook, mapped onto the code.

One switch is a fine table

Here’s the dashboard’s switch. A device has a kind, and the icon depends on it:

enum DeviceKind { LIGHT, THERMOSTAT, LOCK }

record Device(String name, DeviceKind kind) { }
class Dashboard {
    String icon(Device d) {
        switch (d.kind()) {
            case LIGHT: return "bulb";
            case THERMOSTAT: return "flame";
            case LOCK: return "padlock";
            default: return "?";
        }
    }
}

Read on its own, it’s good code. The whole table fits on one screen. It’s easy to scan, and easy to debug. Even the default makes sense: an old-style switch statement that returns a value needs one, or it won’t compile.

Why it hurts: the same switch, everywhere

The trouble is that this decision isn’t made once. The energy report switches on the same kind, and so does the tap handler:

class EnergyReport {
    int watts(Device d) {
        switch (d.kind()) {
            case LIGHT: return 9;
            case THERMOSTAT: return 3;
            case LOCK: return 1;
            default: return 0;
        }
    }
}
class TapHandler {
    void onTap(Device d) {
        switch (d.kind()) {
            case LIGHT: toggle(d); break;
            case THERMOSTAT: openSlider(d); break;
            case LOCK: askForPin(d); break;
            default: break;
        }
    }
}

(The wattages are made-up example values.) Search the project, and the same switch turns up in seven places: also Settings, VoiceAssistant, Notifications and Export.

Now add CAMERA to the enum. Nothing else changes, so everything compiles. And at run time, the camera walks into every default: a question mark, zero watts, and a tap that does nothing. The default branch didn’t make the code safe. It made the mistake quiet.

Adding CAMERA to the DeviceKind enum: each of the seven switches on d.kind() lacks a camera case, so the camera falls into each default branch: the dashboard shows a question mark, the energy report says 0 watts, the tap handler does nothing, and four more switches behave wrongly. Adding CAMERA to the DeviceKind enum: each of the seven switches on d.kind() lacks a camera case, so the camera falls into each default branch: the dashboard shows a question mark, the energy report says 0 watts, the tap handler does nothing, and four more switches behave wrongly.
One new kind, seven places to find and edit.

One new kind, and seven places to find and edit. That’s Shotgun Surgery, with the repeated switch as its cause.

How to spot it

  1. The same selector, switched on in more than one place. Search for switch (d.kind()).
  2. Defaults that return a placeholder, like a question mark or a zero, instead of failing.
  3. Chains of if and else on the same kind count too: if (d.kind() == LIGHT) … else if …. Changing the keyword doesn’t change the smell.
  4. Adding a kind starts with a search. Then the decision lives in too many places.

The key insight: one switch is a choice

So is the switch itself the problem? Fowler and Beck revisited that. The first edition of Refactoring (1999) called this smell “Switch Statements”; the second edition (2018) renamed it Repeated Switches: polymorphism is common now and switches have improved, so the focus is the same conditional logic showing up in several places (paraphrased).

One switch is fine. The trouble is the same switch in many places. Right now, the answers are grouped by question: one switch per row. Turn the grouping around. Give each kind one place that holds all of its answers: its own class. A new kind is then one new card, like the dragon.

LIGHTTHERMOSTATLOCKCAMERA (new)
iconbulbflamepadlockcamera
watts9314
onTaptogglesliderPINlive view

Read the table by rows and you get switches; read it by columns and you get classes.

One switch is a choice. The same switch everywhere is a smell.

The fix: a class for each kind

The refactoring comes in two steps. First, Replace Type Code with Subclasses: an interface with the three questions, and a class for each kind.

interface Device {
    String icon();
    int watts();
    void onTap();
}

Then, Replace Conditional with Polymorphism (see Polymorphism). Each case moves out of its switch, into its kind’s class. The light’s three answers now live together:

class Light implements Device {
    private boolean on;

    public String icon() { return "bulb"; }
    public int watts() { return 9; }
    public void onTap() { on = !on; }
}

The camera is one new class. And if it forgets to answer one of the questions, it doesn’t compile: Camera is not abstract and does not override abstract method onTap() in Device. The compiler won’t print a card with a blank box. The default branch could never do that.

class Camera implements Device {
    public String icon() { return "camera"; }
    public int watts() { return 4; }
    public void onTap() { showLiveView(); }

    private void showLiveView() { /* open the stream */ }
}

The callers stop switching. They ask the device, and dynamic dispatch picks the right method at run time:

String icon = device.icon();
int total = devices.stream().mapToInt(Device::watts).sum();
device.onTap();
Class diagram: the Device interface declares icon, watts and onTap. Light, Thermostat, Lock and Camera each implement all three. Class diagram: the Device interface declares icon, watts and onTap. Light, Thermostat, Lock and Camera each implement all three.
Each kind answers its own questions.

The one switch that stays: making the objects

One switch does stay. Something has to turn the word “camera” from a config file into a Camera object:

static Device fromConfig(String kind) {
    return switch (kind) {
        case "light" -> new Light();
        case "thermostat" -> new Thermostat();
        case "lock" -> new Lock();
        case "camera" -> new Camera();
        default -> throw new IllegalArgumentException(kind);
    };
}

That switch lives once, at the edge, where objects are made. And its default fails loudly, on a kind it doesn’t know. refactoring.guru lists factories as a place where a switch is fine. It’s the game’s setup sheet: one card for each piece in the box.

Switch once. Then let the objects answer.

The other direction: when new operations outnumber new kinds

But polymorphism has a price. A new kind is cheap, but a new question is expensive. Add “night mode”, and you edit every class. That’s the rulebook’s strength: a new topic, like defending, is one new chapter. With cards, you reprint every card.

So if your kinds rarely change and new questions keep coming, keep the switch. But write it as a switch expression, with no default:

int watts(DeviceKind kind) {
    return switch (kind) {
        case LIGHT -> 9;
        case THERMOSTAT -> 3;
        case LOCK -> 1;
        case CAMERA -> 4;
    };
}

Now Java checks that every kind is covered. Leave out CAMERA, and it’s a compile error (the switch expression does not cover all possible input values), in every switch that forgot it. The design notes for switch expressions (JEP 361) make the same point: an explicit default would have hidden that error. Note the difference: old-style switch statements over an enum are not checked this way; switch expressions, and switches that use patterns, are.

The trade-off even has a name: the expression problem (Philip Wadler, 1998).

Decision: if new kinds are added more often than new operations, use polymorphism, one class per kind. If new operations are added more often and the set of kinds is fixed, use an exhaustive switch expression over an enum or sealed type with no default. Either way keep one switch where objects are created. Decision: if new kinds are added more often than new operations, use polymorphism, one class per kind. If new operations are added more often and the set of kinds is fixed, use an exhaustive switch expression over an enum or sealed type with no default. Either way keep one switch where objects are created.
New kinds? Polymorphism. New operations? An exhaustive switch.

A second example: bank transactions

Here’s a realistic case for that. A bank has three kinds of transaction (deposits, withdrawals and transfers), and they almost never change:

sealed interface Transaction
        permits Deposit, Withdrawal, Transfer { }

record Deposit(BigDecimal amount)
        implements Transaction { }
record Withdrawal(BigDecimal amount)
        implements Transaction { }
record Transfer(BigDecimal amount, String to)
        implements Transaction { }

But many teams need something from them. The statement printer, the fraud check and the tax report each need their own operation. Putting statementLine(), fraudScore() and taxCategory() into the transaction types would drag three teams’ rules into one place. So each team owns its own switch:

String statementLine(Transaction t) {
    return switch (t) {
        case Deposit d -> "+" + d.amount();
        case Withdrawal w -> "-" + w.amount();
        case Transfer x -> "-" + x.amount() + " to " + x.to();
    };
}

The interface is sealed (Java 17), so Java knows every kind, and a pattern switch over it (Java 21) needs no default. When the bank adds a Fee, the compiler lists every switch that needs it.

The sealed Transaction interface with Deposit, Withdrawal and Transfer is switched over by three separate teams: statement, fraud check and tax report. Adding Fee to the permits list makes each of the three switches fail to compile until it handles Fee. The sealed Transaction interface with Deposit, Withdrawal and Transfer is switched over by three separate teams: statement, fraud check and tax report. Adding Fee to the permits list makes each of the three switches fail to compile until it handles Fee.
A closed set of kinds, an open set of operations.

Commonly confused: State, Strategy and dynamic dispatch

Two patterns also replace conditionals with objects, so how do you choose?

  • If the kind never changes for an object’s life, use subclasses. A light stays a light.
  • If behavior changes as the object’s state changes, like a lock that’s locked, open or jammed, that’s the State pattern.
  • If the caller picks the behavior, like an eco or a comfort heating schedule, that’s the Strategy pattern.

And under all three is dynamic dispatch: the call finds the right method at run time.

Choosing among subclasses, State and Strategy. Does the kind ever change during the object's life? No: subclasses. Does behavior change with the object's state over time? Yes: State pattern. Does the caller choose the behavior? Yes: Strategy pattern. All three rely on dynamic dispatch. Choosing among subclasses, State and Strategy. Does the kind ever change during the object's life? No: subclasses. Does behavior change with the object's state over time? Yes: State pattern. Does the caller choose the behavior? Yes: Strategy pattern. All three rely on dynamic dispatch.
Same mechanism, three reasons.

Myths, and when a switch is fine

  • “Every switch is a smell.” No: that’s why the smell was renamed.
  • “A default makes it safe.” No: it hides the missing case.
  • “If-else chains are fine.” No: the keyword doesn’t matter.

So when is a switch fine? When it’s the only one, and does something simple. When it lives in the factory. And when the kinds are fixed, and the switch is exhaustive.

Recap

The smell is the same decision, about the same kind, made in many places. Give each kind a class, keep one switch where objects are made, and when the kinds are fixed, switch exhaustively.

Recap chain: count the copies, a class for each kind, one switch at the edge, and for fixed kinds an exhaustive switch. Recap chain: count the copies, a class for each kind, one switch at the edge, and for fixed kinds an exhaustive switch.
Switch once. Then let the objects answer.

That’s the move behind all four smells in this series. A clump, a long list, a primitive and a repeated switch each get a name and a home: Data Clumps, Long Parameter List, Primitive Obsession and this one.

Checklist:

  • Is the same switch (or if chain) on the same kind in more than one class?
  • Does any default return a placeholder instead of failing?
  • Does adding a kind start with a project-wide search?
  • Do kinds change more often than operations (polymorphism), or the other way round (exhaustive switch)?
  • Is the one remaining switch at the edge, where objects are created?

Switch once. Then let the objects answer.

Further reading