Techniquecore
Replace conditional with polymorphism
Also called replace switch with polymorphism, replace type code with polymorphism.
When a switch on a type code is repeated in several functions, make a class for each case and move each branch into a method of its class, so that the call dispatches to the right code with no switch.
- Family
- refactoring
- Intent
- Let each case carry its own behavior, in place of a switch on its type.
Purpose
A switch on a type code says, in one place, what each kind of thing does. When the same switch occurs in several functions, a change to one kind, or an added kind, must find each switch. This is the repeated switches smell.
Replace conditional with polymorphism makes a class for each kind and moves each branch of the switch into a method of that class. A call to the method then runs the code for the kind of object, by dynamic dispatch, and the switch is gone. The catalogue card turns a switch on the type of a bird, which computes its plumage, into a class for each type of bird, each with a plumage getter.1 The refactoring is in both editions of the book.23 The book also uses polymorphism for a variation: a base class has the usual behavior, and a subclass overrides only the case that is different.3
The refactoring has a functional form. In a language with sum types and pattern matching, the cases are the variants of one type, and each operation is one function that matches on the variant. The compiler can then report a match that misses a variant. The two forms make different changes small. With classes, an added kind is one added class, and an added operation is a method in each class. With a sum type, an added operation is one added function, and an added kind is a branch in each match. That trade-off is the expression problem.
Steps
- If the classes do not exist yet, make a class for each case, and a factory function that returns the right class for a type code.3
- Change the callers to use the factory.
- Move the function with the conditional into the base class, if it is not there.
- In one subclass, write a method that overrides the function, and copy into it the branch for that case. Test.
- Repeat for each case.
- Leave the default case in the base class. If there is no default, make the base method abstract or make it throw.
Example
A messaging service computes the cost of a message, and the delay before it is sent, with a switch on the channel in each function. After the refactoring, each channel is a class with both methods. The functional form, with a sum type and a match, is in the Rust example.
import assert from "node:assert/strict";
function costBefore(m) {
switch (m.channel) {
case "email": return 0;
case "sms": return Math.ceil(m.text.length / 160) * 7;
case "push": return m.urgent ? 1 : 0;
default: throw new Error(`unknown channel ${m.channel}`);
}
}
function delayBefore(m) {
switch (m.channel) {
case "email": return 60;
case "sms": return m.urgent ? 0 : 30;
case "push": return 0;
default: throw new Error(`unknown channel ${m.channel}`);
}
}
class Message {
constructor(text, urgent) { Object.assign(this, { text, urgent }); }
get cost() { throw new Error("subclass must define cost"); }
get delaySeconds() { return 0; }
}
class Email extends Message {
get cost() { return 0; }
get delaySeconds() { return 60; }
}
class Sms extends Message {
get cost() { return Math.ceil(this.text.length / 160) * 7; }
get delaySeconds() { return this.urgent ? 0 : 30; }
}
class Push extends Message {
get cost() { return this.urgent ? 1 : 0; }
}
const CLASSES = { email: Email, sms: Sms, push: Push };
function message({ channel, text, urgent }) {
const C = CLASSES[channel];
if (!C) throw new Error(`unknown channel ${channel}`);
return new C(text, urgent);
}
for (const channel of ["email", "sms", "push"]) for (const urgent of [false, true])
for (const text of ["hi", "x".repeat(161)]) {
const data = { channel, text, urgent };
assert.equal(message(data).cost, costBefore(data));
assert.equal(message(data).delaySeconds, delayBefore(data));
}
assert.throws(() => message({ channel: "fax", text: "", urgent: false }));
console.log("replace conditional with polymorphism: tests pass");
replace conditional with polymorphism: tests pass
The factory still has one switch, as a map from the channel name to a class. That switch is the only one: each operation that a channel needs is now a method in each class. Push uses the default delay from the base class.
| Language | What the example shows |
|---|---|
| JavaScript | a class for each channel and a factory, as above |
| Python | the class form, and the match form on frozen dataclasses with the match statement |
| Java | a sealed interface with records, and a switch on the type that the compiler checks for all cases |
| Go | an interface with a type for each channel |
| Rust | the functional form: an enum and a match, which does not compile if a variant is missing |
import math
from dataclasses import dataclass
# The class form: each channel carries its own code.
class Message:
def __init__(self, text: str, urgent: bool) -> None:
self.text, self.urgent = text, urgent
def cost(self) -> int:
raise NotImplementedError
def delay_seconds(self) -> int:
return 0
class Email(Message):
def cost(self) -> int:
return 0
def delay_seconds(self) -> int:
return 60
class Sms(Message):
def cost(self) -> int:
return math.ceil(len(self.text) / 160) * 7
def delay_seconds(self) -> int:
return 0 if self.urgent else 30
class Push(Message):
def cost(self) -> int:
return 1 if self.urgent else 0
# The match form: the cases are plain data, and each operation is one function.
@dataclass(frozen=True)
class EmailMsg:
text: str
@dataclass(frozen=True)
class SmsMsg:
text: str
urgent: bool
@dataclass(frozen=True)
class PushMsg:
urgent: bool
def cost(m: EmailMsg | SmsMsg | PushMsg) -> int:
match m:
case EmailMsg():
return 0
case SmsMsg(text=text):
return math.ceil(len(text) / 160) * 7
case PushMsg(urgent=urgent):
return 1 if urgent else 0
raise TypeError(m)
for urgent in (False, True):
for text in ("hi", "x" * 161):
assert Email(text, urgent).cost() == cost(EmailMsg(text))
assert Sms(text, urgent).cost() == cost(SmsMsg(text, urgent))
assert Push(text, urgent).cost() == cost(PushMsg(urgent))
assert Sms("x" * 161, False).cost() == 14 and Push("", True).delay_seconds() == 0
print("replace conditional with polymorphism: tests pass")
replace conditional with polymorphism: tests pass
When no case matches, a match statement does nothing, and the function would return None. The raise at the end makes a missed case fail at once.
public class Main {
sealed interface Message permits Email, Sms, Push {}
record Email(String text) implements Message {}
record Sms(String text, boolean urgent) implements Message {}
record Push(boolean urgent) implements Message {}
// The switch covers every permitted type, so it needs no default.
// A type added to the permits list and not to the switch fails to compile.
static int cost(Message m) {
return switch (m) {
case Email e -> 0;
case Sms s -> (s.text().length() + 159) / 160 * 7;
case Push p -> p.urgent() ? 1 : 0;
};
}
public static void main(String[] args) {
if (cost(new Email("hi")) != 0) throw new AssertionError("email");
if (cost(new Sms("x".repeat(161), false)) != 14) throw new AssertionError("sms");
if (cost(new Push(true)) != 1) throw new AssertionError("push");
System.out.println("replace conditional with polymorphism: tests pass");
}
}
replace conditional with polymorphism: tests pass
package main
import "fmt"
// Message is the interface that each channel type implements.
type Message interface {
Cost() int
DelaySeconds() int
}
type Email struct{ Text string }
type Sms struct {
Text string
Urgent bool
}
type Push struct{ Urgent bool }
func (Email) Cost() int { return 0 }
func (Email) DelaySeconds() int { return 60 }
func (s Sms) Cost() int { return (len(s.Text) + 159) / 160 * 7 }
func (s Sms) DelaySeconds() int {
if s.Urgent {
return 0
}
return 30
}
func (p Push) Cost() int {
if p.Urgent {
return 1
}
return 0
}
func (Push) DelaySeconds() int { return 0 }
func costBefore(channel, text string, urgent bool) int {
switch channel {
case "email":
return 0
case "sms":
return (len(text) + 159) / 160 * 7
default: // "push"
if urgent {
return 1
}
return 0
}
}
func main() {
long := string(make([]byte, 161))
for _, urgent := range []bool{false, true} {
for _, text := range []string{"hi", long} {
msgs := map[string]Message{"email": Email{text}, "sms": Sms{text, urgent}, "push": Push{urgent}}
for ch, m := range msgs {
if m.Cost() != costBefore(ch, text, urgent) {
panic(ch)
}
}
}
}
fmt.Println("replace conditional with polymorphism: tests pass")
}
replace conditional with polymorphism: tests pass
// The functional form: the cases are the variants of one enum, and each
// operation is one function with a match. A match that misses a variant
// does not compile.
enum Message {
Email,
Sms { text: String, urgent: bool },
Push { urgent: bool },
}
fn cost(m: &Message) -> usize {
match m {
Message::Email => 0,
Message::Sms { text, .. } => text.len().div_ceil(160) * 7,
Message::Push { urgent } => usize::from(*urgent),
}
}
fn delay_seconds(m: &Message) -> u32 {
match m {
Message::Email => 60,
Message::Sms { urgent: true, .. } | Message::Push { .. } => 0,
Message::Sms { urgent: false, .. } => 30,
}
}
fn main() {
let email = Message::Email;
let sms = Message::Sms {
text: "x".repeat(161),
urgent: false,
};
let push = Message::Push { urgent: true };
assert_eq!(cost(&email), 0);
assert_eq!(cost(&sms), 14);
assert_eq!(cost(&push), 1);
assert_eq!(delay_seconds(&email), 60);
assert_eq!(delay_seconds(&sms), 30);
assert_eq!(delay_seconds(&push), 0);
println!("replace conditional with polymorphism: tests pass");
}
replace conditional with polymorphism: tests pass
When to use
- The same switch in several places. Without the refactoring, each added case changes every switch.
- A base case with variations. A subclass that overrides one method shows the difference from the usual behavior.3
- Behavior that depends on a type code. A field such as
type,kindorchannelthat the code tests in many places.
Pitfalls
One switch. A single switch in one function is a clear and complete list of the cases. Classes for it spread the list over many places. Keep it.
The wrong axis of change. If added operations come more often than added kinds, the class form makes each operation a change to every class. The sum-type form with pattern matching fits that case better. See The expression problem.
A missed case. With classes, a subclass that does not override an abstract method fails only at run time in a dynamic language. With a sum type in a language that checks matches, a missed variant is a compile error. In JavaScript or Python, a base method that throws makes the miss visible at once.
Tools that do it
This refactoring is a sequence of steps, not one action of a tool.
References
- Martin Fowler, Catalog of Refactorings, Replace Conditional with Polymorphism, the entry
- Martin Fowler, Refactoring, Improving the Design of Existing Code, Addison-Wesley, 1999, Chapter 9, Simplifying Conditional Expressions, Replace Conditional with Polymorphism
- Martin Fowler, Refactoring, Improving the Design of Existing Code, second edition, Addison-Wesley, 2018, Chapter 10, Simplifying Conditional Logic, Replace Conditional with Polymorphism, motivation, mechanics and the examples with a type code and with a variation on a base case
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Visual | V0 none |
|
| Writing | W4 complete |
|
Tag WPBMPA Edit this page History Report an error Markdown