Repeated Switches is a smell where the same switch, match or if/else chain on a type code appears in several functions, sometimes in several modules. Each copy branches on the same values: a tier, a status, a plan, a kind. Each copy answers a different question about them.
One switch is fine. The problem starts with the second and third copies. The knowledge of what a type code means is no longer in one place. It is spread across every function that branches on it. When you add a new value, you have to find every switch, and the compiler or linter will not always point you to them. Missing one usually shows up as a wrong number in production, not as a crash.
Interviewers like this smell because the textbook fix is polymorphism. They also want to hear when a plain lookup table is the better answer.
Signs
How to spot it in a review.
- The same set of
caselabels, such as"hot","cool"and"archive", appears in three or more functions. - Adding one new enum value or string constant forces edits in several files, and code review is the main thing that catches a forgotten one.
- Several switches end with the same
default: throw new Error("Unknown ...")fallback. - Functions are named after a question about the type, like
feeFor,delayFororlabelFor, and each one is just a switch on that type. - The type code is a bare string or integer passed around, with no object that owns its behaviour.
What it looks like
A typical case, in three languages.
type Tier = "hot" | "cool" | "archive";
interface StoredObject {
key: string;
sizeGb: number;
tier: Tier;
}
// billing/storage.ts
export function monthlyStorageCost(obj: StoredObject): number {
switch (obj.tier) {
case "hot":
return obj.sizeGb * 0.023;
case "cool":
return obj.sizeGb * 0.01;
case "archive":
return obj.sizeGb * 0.002;
default:
throw new Error(`Unknown tier: ${obj.tier}`);
}
}
// billing/retrieval.ts
export function retrievalFee(obj: StoredObject): number {
switch (obj.tier) {
case "hot":
return 0;
case "cool":
return obj.sizeGb * 0.01;
case "archive":
return obj.sizeGb * 0.05;
default:
throw new Error(`Unknown tier: ${obj.tier}`);
}
}
// restore/scheduler.ts
export function retrievalDelayHours(obj: StoredObject): number {
switch (obj.tier) {
case "hot":
case "cool":
return 0;
case "archive":
return 12;
default:
throw new Error(`Unknown tier: ${obj.tier}`);
}
}
const backup: StoredObject = { key: "db/2024-05-01.tar", sizeGb: 500, tier: "archive" };
console.log(monthlyStorageCost(backup), retrievalFee(backup), retrievalDelayHours(backup));from dataclasses import dataclass
from typing import Literal
Tier = Literal["hot", "cool", "archive"]
@dataclass(frozen=True)
class StoredObject:
key: str
size_gb: float
tier: Tier
# billing/storage.py
def monthly_storage_cost(obj: StoredObject) -> float:
match obj.tier:
case "hot":
return obj.size_gb * 0.023
case "cool":
return obj.size_gb * 0.01
case "archive":
return obj.size_gb * 0.002
case _:
raise ValueError(f"Unknown tier: {obj.tier}")
# billing/retrieval.py
def retrieval_fee(obj: StoredObject) -> float:
match obj.tier:
case "hot":
return 0.0
case "cool":
return obj.size_gb * 0.01
case "archive":
return obj.size_gb * 0.05
case _:
raise ValueError(f"Unknown tier: {obj.tier}")
# restore/scheduler.py
def retrieval_delay_hours(obj: StoredObject) -> int:
match obj.tier:
case "hot" | "cool":
return 0
case "archive":
return 12
case _:
raise ValueError(f"Unknown tier: {obj.tier}")
backup = StoredObject(key="db/2024-05-01.tar", size_gb=500, tier="archive")
print(monthly_storage_cost(backup), retrieval_fee(backup), retrieval_delay_hours(backup))<?php
final class StoredObject
{
public function __construct(
public readonly string $key,
public readonly float $sizeGb,
public readonly string $tier, // 'hot' | 'cool' | 'archive'
) {}
}
// Billing/Storage.php
function monthlyStorageCost(StoredObject $obj): float
{
switch ($obj->tier) {
case 'hot':
return $obj->sizeGb * 0.023;
case 'cool':
return $obj->sizeGb * 0.01;
case 'archive':
return $obj->sizeGb * 0.002;
default:
throw new InvalidArgumentException("Unknown tier: {$obj->tier}");
}
}
// Billing/Retrieval.php
function retrievalFee(StoredObject $obj): float
{
switch ($obj->tier) {
case 'hot':
return 0.0;
case 'cool':
return $obj->sizeGb * 0.01;
case 'archive':
return $obj->sizeGb * 0.05;
default:
throw new InvalidArgumentException("Unknown tier: {$obj->tier}");
}
}
// Restore/Scheduler.php
function retrievalDelayHours(StoredObject $obj): int
{
switch ($obj->tier) {
case 'hot':
case 'cool':
return 0;
case 'archive':
return 12;
default:
throw new InvalidArgumentException("Unknown tier: {$obj->tier}");
}
}
$backup = new StoredObject('db/2024-05-01.tar', 500, 'archive');
echo monthlyStorageCost($backup), ' ', retrievalFee($backup), ' ', retrievalDelayHours($backup), PHP_EOL;This code is from an object storage service. Three modules owned by two teams each switch on tier. Suppose product asks for a deep-archive tier at 0.001 per GB, a 0.10 per GB retrieval fee and a 48-hour delay. Then someone has to find and edit all three switches. In PHP, where tier is a bare string, nothing warns you if the scheduler is skipped. The new tier then fails at runtime with an exception, or gets a silently wrong delay if a later edit turns default into return 0.
Why it happens
How code ends up like this.
- A new type value touches every switch, so a small product change becomes a search across the codebase.
- A forgotten branch often fails quietly through a
defaultcase. The result is wrong billing or scheduling, not a clear error. - The rules for one tier are spread across many files. Nobody can read in one place what
archivemeans. - Each switch file depends on the full list of type codes, which couples unrelated modules to the same enum.
- Tests have to cover every combination of function and type separately, and gaps hide easily.
Treatment
The refactorings that cure it, and when to choose each.
- Replace Primitive with Object: Give Rule-Bearing Values a Type
First turn the bare
tierstring into aStorageTiertype or value object. That gives the behaviour a home and stops invalid strings from getting in. - Replace Conditional with Polymorphism: One Class per Case
Give each tier its own class (
HotTier,CoolTier,ArchiveTier) withmonthlyCost,retrievalFeeandretrievalDelayHours. Then each switch becomes one method call, and a new tier is one new class. - Extract function: give a fragment a name
If a switch is buried inside a larger function, pull it out into its own function first so it can be moved and replaced cleanly.
- Move Function: Put Behaviour Next to the Data It Uses
Move the extracted per-tier logic from the billing and scheduler modules onto the tier type, so callers ask the tier instead of inspecting it.
- Introduce Special Case: Replace Repeated Null Checks With an Object
If several switches share the same fallback for a missing or legacy tier, model it as a special-case tier object instead of repeating the
defaultbranch.
Payoff
What you get once it's gone.
- Adding a tier means writing one class or one table entry. The type system or a single registry shows you everything it must provide.
- All rules for a tier sit together, so pricing reviews and audits read one file.
- Billing and scheduling code stops depending on the list of tier names.
- Tests are organised per tier, and a missing method fails at compile time or at construction, not in production.
When to leave it
Sometimes it's not worth fixing.
- There is only one switch on the type code, typically in a factory or parser that turns input into objects. That switch is the right place for the branching.
- The branches only map values to constants. A single lookup table such as
const TIER_PRICING = { hot: {...}, cool: {...} }removes the duplication without a class hierarchy. - The set of types is fixed and small, but the set of operations keeps growing. Here a switch per operation, with exhaustiveness checking from TypeScript's
neveror a static analyser, can be easier to extend than adding a method to every class. - The code is a short-lived script or a migration that will be deleted after one run.
Common questions
Short answers to the usual doubts.
Is polymorphism always the fix for repeated switches?
No. If every branch just returns numbers, a lookup table keyed by the type code fixes the duplication with less code. Use classes when the branches contain real behaviour that differs per type, like different formulas, side effects or validation rules. In the storage example a table would work today. Classes start to pay off once archive retrieval needs its own scheduling logic.
Doesn't TypeScript's exhaustive switch checking solve this?
It reduces the risk. With a union type and a never check in default, the compiler flags switches that miss a new value. But you still edit several files for every new type, and the knowledge stays scattered. It is a good safety net while you refactor, and it is enough when the switches truly belong to different modules.
How is this different from a long switch statement?
A long switch is about the size of one conditional. Repeated Switches is about duplication: several conditionals, possibly short, that branch on the same type code. You can have three-line switches that are still a serious smell because there are six of them.
How should I talk about this smell in an interview?
Point to the duplicated case labels. Explain the cost of adding a new value, such as a deep-archive tier. Then propose moving the behaviour onto the type through polymorphism or a table, and give your reason for choosing one. Mention that a single switch in a factory is fine, so it's clear you are not applying the rule blindly.
Where does the remaining switch go after the refactoring?
Usually you keep exactly one, at the boundary where a stored string like "archive" is turned into a tier object. That might be a factory function, a constructor map or a deserializer. Everywhere else works with the object and never inspects the code.