# Switch StatementsOne 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.

{{< lesson-video youtube="xCPv0IA-xaY" title="Switch Statements" >}}

## 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.

```mermaid {alt="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." caption="The rulebook, mapped onto the code."}
flowchart LR
  A["a chapter per topic"] --> A2["a switch per operation"]
  B["the pieces"] --> B2["LIGHT, THERMOSTAT, LOCK"]
  C["the expansion's dragon"] --> C2["CAMERA"]
  D["the missed entry"] --> D2["a switch nobody updated"]
  E["basic attack"] --> E2["default branch"]
  class C2 c4
  class D2,E2 bad
```

## One switch is a fine table

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

```java
enum DeviceKind { LIGHT, THERMOSTAT, LOCK }

record Device(String name, DeviceKind kind) { }
```

```java
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:

```java
class EnergyReport {
    int watts(Device d) {
        switch (d.kind()) {
            case LIGHT: return 9;
            case THERMOSTAT: return 3;
            case LOCK: return 1;
            default: return 0;
        }
    }
}
```

```java
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.

```mermaid {alt="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." caption="One new kind, seven places to find and edit."}
flowchart LR
  K["+ CAMERA"] --> D["Dashboard.icon<br/>default: ?"]
  K --> E["EnergyReport.watts<br/>default: 0"]
  K --> T["TapHandler.onTap<br/>default: nothing"]
  K --> O["Settings, VoiceAssistant,<br/>Notifications, Export"]
  class K c4
  class D,E,T,O bad
```

One new kind, and seven places to find and edit. That's
[Shotgun Surgery](/code-smells/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.

| | LIGHT | THERMOSTAT | LOCK | CAMERA (new) |
|---|---|---|---|---|
| **icon** | bulb | flame | padlock | camera |
| **watts** | 9 | 3 | 1 | 4 |
| **onTap** | toggle | slider | PIN | live 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.

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

Then, **Replace Conditional with Polymorphism** (see [Polymorphism](/fundamentals/polymorphism/)). Each case moves out of its switch, into its kind's
class. The light's three answers now live together:

```java
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.

```java
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](/fundamentals/dynamic-dispatch/) picks the right method at run time:

```java
String icon = device.icon();
int total = devices.stream().mapToInt(Device::watts).sum();
device.onTap();
```

```mermaid {alt="Class diagram: the Device interface declares icon, watts and onTap. Light, Thermostat, Lock and Camera each implement all three." caption="Each kind answers its own questions."}
classDiagram
  class Device {
    <<interface>>
    icon() String
    watts() int
    onTap() void
  }
  class Light
  class Thermostat
  class Lock
  class Camera
  Device <|.. Light
  Device <|.. Thermostat
  Device <|.. Lock
  Device <|.. Camera
```

## 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:

```java
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:

```java
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).

```mermaid {alt="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." caption="New kinds? Polymorphism. New operations? An exhaustive switch."}
flowchart TD
  Q{"what changes more often?"}
  Q -->|"new kinds"| P["polymorphism<br/>one class per kind"]
  Q -->|"new operations,<br/>fixed kinds"| X["exhaustive switch<br/>no default"]
  P --> F["one switch in the factory"]
  class P,X good
  class F muted
```

## 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:

```java
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:

```java
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.

```mermaid {alt="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." caption="A closed set of kinds, an open set of operations."}
flowchart LR
  T["sealed Transaction<br/>Deposit · Withdrawal · Transfer<br/>+ Fee"] --> S["statement<br/>switch (t)"]
  T --> F["fraud check<br/>switch (t)"]
  T --> X["tax report<br/>switch (t)"]
  class T c6
  class S,F,X warn
```

## 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](/patterns/state-pattern/).
- If **the caller picks** the behavior, like an eco or a comfort heating schedule, that's the
  [Strategy pattern](/patterns/strategy-pattern/).

And under all three is [dynamic dispatch](/fundamentals/dynamic-dispatch/): the call finds the
right method at run time.

```mermaid {alt="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." caption="Same mechanism, three reasons."}
flowchart TD
  A{"does the kind ever change?"} -->|no| S["subclasses"]
  A -->|yes| B{"does it change with<br/>the object's own state?"}
  B -->|yes| ST["State pattern"]
  B -->|"no, the caller picks"| SG["Strategy pattern"]
  class S,ST,SG good
```

## 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.

```mermaid {alt="Recap chain: count the copies, a class for each kind, one switch at the edge, and for fixed kinds an exhaustive switch." caption="Switch once. Then let the objects answer."}
flowchart LR
  A["count the copies"] --> B["a class for each kind"] --> C["one switch at the edge"] --> D["fixed kinds: exhaustive"]
  class D good
```

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](/code-smells/data-clumps/),
[Long Parameter List](/code-smells/long-parameter-list/),
[Primitive Obsession](/code-smells/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

- Martin Fowler and Kent Beck, *Refactoring* (2nd ed., 2018), chapter 3, "Repeated Switches".
- Refactoring catalog: [Replace Conditional with Polymorphism](https://refactoring.com/catalog/replaceConditionalWithPolymorphism.html),
  [Replace Type Code with Subclasses](https://refactoring.com/catalog/replaceTypeCodeWithSubclasses.html).
- [JEP 361: Switch Expressions](https://openjdk.org/jeps/361), [JEP 409: Sealed Classes](https://openjdk.org/jeps/409),
  [JEP 441: Pattern Matching for switch](https://openjdk.org/jeps/441).
- [Expression problem](https://en.wikipedia.org/wiki/Expression_problem) (Philip Wadler, 1998).
