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 20class Membership:
def __init__(self, kind: str, seats: int) -> None:
self.kind = kind
self.seats = seats
def monthly_charge(self) -> int:
match self.kind:
case "hot_desk":
return 180
case "dedicated_desk":
return 320
case "private_office":
return self.seats * 495 if self.seats >= 4 else self.seats * 550
case _:
raise AssertionError(f"unreachable kind: {self.kind}")
def included_room_hours(self) -> int:
match self.kind:
case "hot_desk":
return 2
case "dedicated_desk":
return 6
case "private_office":
return self.seats * 4
case _:
raise AssertionError(f"unreachable kind: {self.kind}")
def create_membership(kind: str, seats: int) -> Membership:
if kind not in ("hot_desk", "dedicated_desk", "private_office"):
raise ValueError(f"Unknown membership kind: {kind}")
return Membership(kind, seats)
office = create_membership("private_office", 5)
print(office.monthly_charge(), office.included_room_hours()) # 2475 20<?php
final class Membership
{
public function __construct(
public readonly string $kind,
public readonly int $seats,
) {}
public function monthlyCharge(): int
{
return match ($this->kind) {
'hot_desk' => 180,
'dedicated_desk' => 320,
'private_office' => $this->seats >= 4 ? $this->seats * 495 : $this->seats * 550,
};
}
public function includedRoomHours(): int
{
return match ($this->kind) {
'hot_desk' => 2,
'dedicated_desk' => 6,
'private_office' => $this->seats * 4,
};
}
}
function createMembership(string $kind, int $seats): Membership
{
if (!in_array($kind, ['hot_desk', 'dedicated_desk', 'private_office'], true)) {
throw new InvalidArgumentException("Unknown membership kind: $kind");
}
return new Membership($kind, $seats);
}
$office = createMembership('private_office', 5);
echo $office->monthlyCharge(), ' ', $office->includedRoomHours(), PHP_EOL; // 2475 20After
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 20from abc import ABC, abstractmethod
class Membership(ABC):
def __init__(self, seats: int) -> None:
self.seats = seats
@abstractmethod
def monthly_charge(self) -> int: ...
@abstractmethod
def included_room_hours(self) -> int: ...
class HotDesk(Membership):
def monthly_charge(self) -> int:
return 180
def included_room_hours(self) -> int:
return 2
class DedicatedDesk(Membership):
def monthly_charge(self) -> int:
return 320
def included_room_hours(self) -> int:
return 6
class PrivateOffice(Membership):
def monthly_charge(self) -> int:
return self.seats * 495 if self.seats >= 4 else self.seats * 550
def included_room_hours(self) -> int:
return self.seats * 4
def create_membership(kind: str, seats: int) -> Membership:
match kind:
case "hot_desk":
return HotDesk(seats)
case "dedicated_desk":
return DedicatedDesk(seats)
case "private_office":
return PrivateOffice(seats)
case _:
raise ValueError(f"Unknown membership kind: {kind}")
office = create_membership("private_office", 5)
print(office.monthly_charge(), office.included_room_hours()) # 2475 20<?php
abstract class Membership
{
public function __construct(public readonly int $seats) {}
abstract public function monthlyCharge(): int;
abstract public function includedRoomHours(): int;
}
final class HotDesk extends Membership
{
public function monthlyCharge(): int
{
return 180;
}
public function includedRoomHours(): int
{
return 2;
}
}
final class DedicatedDesk extends Membership
{
public function monthlyCharge(): int
{
return 320;
}
public function includedRoomHours(): int
{
return 6;
}
}
final class PrivateOffice extends Membership
{
public function monthlyCharge(): int
{
return $this->seats >= 4 ? $this->seats * 495 : $this->seats * 550;
}
public function includedRoomHours(): int
{
return $this->seats * 4;
}
}
function createMembership(string $kind, int $seats): Membership
{
return match ($kind) {
'hot_desk' => new HotDesk($seats),
'dedicated_desk' => new DedicatedDesk($seats),
'private_office' => new PrivateOffice($seats),
default => throw new InvalidArgumentException("Unknown membership kind: $kind"),
};
}
$office = createMembership('private_office', 5);
echo $office->monthlyCharge(), ' ', $office->includedRoomHours(), PHP_EOL; // 2475 20Why 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
kindfor 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.
Write or check tests that cover every kind for both
monthlyChargeandincludedRoomHours, plus the error for an unknown kind. Run them and confirm they pass.Make sure every caller builds memberships through
createMembershipand not by calling the constructor directly. Replace any directnew Membership(...)calls and run the tests.Create empty subclasses
HotDesk,DedicatedDeskandPrivateOfficethat extendMembershipand still pass the kind to the parent constructor. Change the factory to return the matching subclass. Run the tests.Copy the private-office branch of
monthlyChargeinto an override onPrivateOffice. Run the tests. In the base switch, the branch is now dead code for that kind.Repeat the previous step for
HotDeskandDedicatedDesk. Then makemonthlyChargeabstract in the base class and delete its switch. Run the tests.Apply the same steps to
includedRoomHours: one override per subclass, then an abstract declaration with no switch. Run the tests.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.