Skip to content

Replace Conditional with Polymorphism: One Class per Case

Learn how to replace a switch on a type code with one subclass per case, in small steps that keep your tests green, with TypeScript, Python and PHP examples.

7 min readRefactoring

Replace Conditional with Polymorphism takes a switch or if chain that branches on a type code and moves each branch into its own class. The caller then asks the object for an answer and does not need to know which kind of object it holds. This guide uses an invented billing module for Harbor Lane, a coworking company that sells three memberships: hot desk, dedicated desk and private office. You will see the code before and after the refactoring in TypeScript, Python and PHP, and a sequence of small steps that keeps the tests passing after each one.

The problem

A situation where the obvious design starts to hurt.

Harbor Lane's Membership class stores a kind string and branches on it in every method. monthlyCharge has one switch and includedRoomHours has another, and both list the same three cases.

When product adds a fourth membership, such as a weekend pass, you have to find every switch on kind and add a branch to each one. If you miss one, it fails at runtime. Each new rule about one membership also makes a method longer that every other membership shares. The knowledge about a private office is spread across many methods when it should sit in one place.

Before and after

The same code, before and after the change.

Before

type MembershipKind = "hot_desk" | "dedicated_desk" | "private_office";

class Membership {
  constructor(readonly kind: MembershipKind, readonly seats: number) {}

  monthlyCharge(): number {
    switch (this.kind) {
      case "hot_desk":
        return 180;
      case "dedicated_desk":
        return 320;
      case "private_office":
        return this.seats >= 4 ? this.seats * 495 : this.seats * 550;
    }
  }

  includedRoomHours(): number {
    switch (this.kind) {
      case "hot_desk":
        return 2;
      case "dedicated_desk":
        return 6;
      case "private_office":
        return this.seats * 4;
    }
  }
}

function createMembership(kind: string, seats: number): Membership {
  if (kind === "hot_desk" || kind === "dedicated_desk" || kind === "private_office") {
    return new Membership(kind, seats);
  }
  throw new Error(`Unknown membership kind: ${kind}`);
}

const office = createMembership("private_office", 5);
console.log(office.monthlyCharge(), office.includedRoomHours()); // 2475 20

After

abstract class Membership {
  constructor(readonly seats: number) {}

  abstract monthlyCharge(): number;
  abstract includedRoomHours(): number;
}

class HotDesk extends Membership {
  monthlyCharge(): number {
    return 180;
  }

  includedRoomHours(): number {
    return 2;
  }
}

class DedicatedDesk extends Membership {
  monthlyCharge(): number {
    return 320;
  }

  includedRoomHours(): number {
    return 6;
  }
}

class PrivateOffice extends Membership {
  monthlyCharge(): number {
    return this.seats >= 4 ? this.seats * 495 : this.seats * 550;
  }

  includedRoomHours(): number {
    return this.seats * 4;
  }
}

function createMembership(kind: string, seats: number): Membership {
  switch (kind) {
    case "hot_desk":
      return new HotDesk(seats);
    case "dedicated_desk":
      return new DedicatedDesk(seats);
    case "private_office":
      return new PrivateOffice(seats);
    default:
      throw new Error(`Unknown membership kind: ${kind}`);
  }
}

const office = createMembership("private_office", 5);
console.log(office.monthlyCharge(), office.includedRoomHours()); // 2475 20

Why it's worth it

What the change buys you.

After the refactoring, only one switch on the type remains, and it lives in the factory. That is the one place where the kind can only be known from a string, because it comes from a form, a database row or an API payload. Everywhere else, the object already knows what it is, so dynamic dispatch picks the right method.

Adding a weekend pass now means writing one new class and one new factory case. In TypeScript and PHP, the compiler or the runtime refuses an incomplete subclass. In Python, ABC raises a TypeError when you instantiate a subclass that misses an abstract method. Before, a missing branch failed silently or late.

Each class is also small enough to read in one go. Everything Harbor Lane knows about private offices, including the volume discount and the room-hour allowance, now sits in PrivateOffice. A change to that pricing cannot affect hot desks by accident.

  • Adding a membership type means writing one new class plus one factory case, not editing every method that branches on the type.
  • The compiler or runtime flags a subclass that forgets to implement a method, instead of a missing branch slipping through.
  • All the rules for one membership type live together, so pricing changes stay local and are easy to review.
  • Each method body shrinks to the logic for a single case, which makes it easier to test in isolation.

Careful with

  • Keep one conditional in a factory. Data from outside arrives as a string or an enum, and something has to map that value to a class.
  • If callers read kind for display or serialization, keep it as an abstract property on each subclass instead of deleting it.
  • A single, small switch that never repeats does not need this refactoring. Splitting it into classes can add more structure than it removes.
  • If an object's kind can change during its lifetime, for example when someone upgrades from hot desk to private office, subclasses do not fit. Consider Replace Type Code with State/Strategy instead.

Step by step

Small, safe steps, with the tests passing after each.

  1. Write or check tests that cover every kind for both monthlyCharge and includedRoomHours, plus the error for an unknown kind. Run them and confirm they pass.

  2. Make sure every caller builds memberships through createMembership and not by calling the constructor directly. Replace any direct new Membership(...) calls and run the tests.

  3. Create empty subclasses HotDesk, DedicatedDesk and PrivateOffice that extend Membership and still pass the kind to the parent constructor. Change the factory to return the matching subclass. Run the tests.

  4. Copy the private-office branch of monthlyCharge into an override on PrivateOffice. Run the tests. In the base switch, the branch is now dead code for that kind.

  5. Repeat the previous step for HotDesk and DedicatedDesk. Then make monthlyCharge abstract in the base class and delete its switch. Run the tests.

  6. Apply the same steps to includedRoomHours: one override per subclass, then an abstract declaration with no switch. Run the tests.

  7. Search the codebase for any remaining reads of kind. If none remain, remove the field and the constructor parameter, and make the base class abstract. Run the tests one last time.

Smells it removes

Smells this refactoring helps remove.

Common questions

Short answers to the usual doubts.

Isn't the switch just moved into the factory?

One switch is moved into the factory. The others are removed. Before the refactoring, every behaviour had its own switch. Afterwards, there is a single mapping from input data to a class, and every behaviour is dispatched polymorphically. The number of switches no longer grows with the number of methods.

Should I use subclasses or an enum with methods?

If each case needs only a few constant values, an enum with fields, or a lookup table, is often simpler. Use subclasses when the cases differ in logic, such as the private office's seat discount, or when they need their own data or collaborators.

How do I explain this refactoring in an interview?

Name the smell: the same switch on a type code appears in several methods. Then explain the fix: create one class per case, move each branch into an override, and leave a single factory. Mention that you would move one branch at a time with tests passing after each step, and point out when you would not apply it.

Does polymorphism make the code slower?

A virtual method call costs about the same as a switch on a small number of cases, and runtimes optimise both well. In a billing module like this one, the difference is negligible. Choose the structure for readability and ease of change.

Next guide5 of 5 · Techniques: simplifying conditionalsIntroduce Special Case: Replace Repeated Null Checks With an ObjectRead the next one