Skip to content

Repeated Switches: the same type-code switch scattered across a codebase

How to spot the same switch on a type code repeated in several places, why it slows every change, and how to refactor it into polymorphism or data.

6 min readCode smellMisused abstractions

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 case labels, 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, delayFor or labelFor, 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));

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 default case. 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 archive means.
  • 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.

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 never or 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.

Next guide2 of 4 · Smells: misused abstractionsRefused Bequest: Subclasses That Reject What They InheritRead the next one