Patterncore
Repeated Switches
Also called switch statements.
A code smell: the same switch or if chain on the same kind of value appears in many functions, so each added case needs an edit in each of them.
- Family
- code-smell
- Intent
- Find the switches that test the same condition in many places, and replace them with one place that knows the cases, often a class for each case.
- Also called
- Switch Statements
Intent
Find the switches that test the same condition in many functions, and give the cases one home. The usual home is a class for each case, with a method for each function that used to switch. Then a case that is added is one class, and no function can miss it.
Problem
A switch on its own is a normal control structure. The first edition of Refactoring named the smell Switch Statements.1 The second edition renames it Repeated Switches. It says that a switch was once treated as bad in itself, and that the smell is the same switch in many places.2
The usual cause is a type code: a field, such as kind or status, that tells which kind of thing a value is. Each function that behaves differently for each kind switches on the field. Refactoring gives the result: when a case is added, the programmer must find all the switches and update each one.2
The forces are these:
- The first switch is the natural way to write the code. The second and third are copies of the first, written where they were needed.
- Nothing links the switches. A search for the type code finds them, if the programmer knows to search.
- A switch with no default case, or with a default that returns a neutral value, does not fail when a case is missing. It gives a wrong answer.
- Languages differ in how much they help. The Python tutorial describes the
matchstatement as one that "takes an expression and compares its value to successive patterns", and notes that "If no case matches, none of the branches is executed."3 The Go specification has a type switch, which "compares types rather than values."4 Neither one warns about a missing case.
Solution
Refactoring names Replace Conditional with Polymorphism as the main fix.2 The catalogue at refactoring.com has the card, and the card for Replace Type Code with Subclasses, which is often the step before it.5
- If the cases are a type code, replace it with a class for each case.
- For each function that switches on the code, add a method with the same name to each class. Move the code of each branch into the class of its case.
- Replace the switch with a call to the method.
When the cases are data, not behaviour, a table is often enough. A map from each case to its values puts the cases in one place without classes.
Example
Two functions switch on the kind of a shape. A triangle is added to the area function, but the perimeter function is not updated, and it returns 0 for a triangle with no error.
import assert from "node:assert/strict";
// Before: each function switches on the kind.
function areaBefore(s) {
switch (s.kind) {
case "circle": return Math.PI * s.r ** 2;
case "square": return s.side ** 2;
case "triangle": return (s.base * s.height) / 2;
default: return 0;
}
}
function perimeterBefore(s) {
switch (s.kind) {
case "circle": return 2 * Math.PI * s.r;
case "square": return 4 * s.side;
default: return 0; // the triangle case was never added
}
}
const t = { kind: "triangle", base: 3, height: 4, sides: [3, 4, 5] };
assert.equal(areaBefore(t), 6);
assert.equal(perimeterBefore(t), 0);
console.log("before: the perimeter of a triangle is 0");
// After: each kind is a class, and each class has all the methods.
class Circle {
constructor(r) { this.r = r; }
area() { return Math.PI * this.r ** 2; }
perimeter() { return 2 * Math.PI * this.r; }
}
class Square {
constructor(side) { this.side = side; }
area() { return this.side ** 2; }
perimeter() { return 4 * this.side; }
}
class Triangle {
constructor(a, b, c) { this.sides = [a, b, c]; }
area() {
const [a, b, c] = this.sides;
const s = (a + b + c) / 2;
return Math.sqrt(s * (s - a) * (s - b) * (s - c));
}
perimeter() { return this.sides.reduce((x, y) => x + y, 0); }
}
const shapes = [new Circle(1), new Square(2), new Triangle(3, 4, 5)];
assert.deepEqual(shapes.map((s) => s.perimeter()), [2 * Math.PI, 8, 12]);
assert.deepEqual(shapes.map((s) => s.area()), [Math.PI, 4, 6]);
console.log("after: tests pass");
before: the perimeter of a triangle is 0
after: tests pass
The second version has no switch. Each class answers for its own kind, so a class that is added must supply both methods, and a call to a missing method fails with a TypeError in place of a wrong number. The cases are in one place per kind, not one place per function.
| Language | What the example shows |
|---|---|
| JavaScript | a class for each shape, as above |
| Python | match on a string in the first version, and classes with an abstract base in the second |
| Java | a switch on a string, then a sealed interface with records; a switch over the sealed type must cover each case |
| Go | a switch on a string, then an interface with a method for each operation |
import math
from abc import ABC, abstractmethod
# Before: each function matches on the kind.
def area_before(s):
match s["kind"]:
case "circle":
return math.pi * s["r"] ** 2
case "square":
return s["side"] ** 2
case "triangle":
return s["base"] * s["height"] / 2
case _:
return 0
def perimeter_before(s):
match s["kind"]:
case "circle":
return 2 * math.pi * s["r"]
case "square":
return 4 * s["side"]
case _:
return 0 # the triangle case was never added
t = {"kind": "triangle", "base": 3, "height": 4}
assert area_before(t) == 6
assert perimeter_before(t) == 0
print("before: the perimeter of a triangle is 0")
# After: each kind is a class, and the base class lists the methods.
class Shape(ABC):
@abstractmethod
def area(self): ...
@abstractmethod
def perimeter(self): ...
class Circle(Shape):
def __init__(self, r):
self.r = r
def area(self):
return math.pi * self.r**2
def perimeter(self):
return 2 * math.pi * self.r
class Square(Shape):
def __init__(self, side):
self.side = side
def area(self):
return self.side**2
def perimeter(self):
return 4 * self.side
class Triangle(Shape):
def __init__(self, a, b, c):
self.sides = (a, b, c)
def area(self):
a, b, c = self.sides
s = (a + b + c) / 2
return math.sqrt(s * (s - a) * (s - b) * (s - c))
def perimeter(self):
return sum(self.sides)
shapes = [Circle(1), Square(2), Triangle(3, 4, 5)]
assert [s.perimeter() for s in shapes] == [2 * math.pi, 8, 12]
assert [s.area() for s in shapes] == [math.pi, 4, 6]
class HalfDone(Shape):
def area(self):
return 0
try:
HalfDone()
except TypeError:
pass
else:
raise AssertionError("a class without perimeter was created")
print("after: tests pass")
before: the perimeter of a triangle is 0
after: tests pass
- The
case _:branch matches any value. Without it, amatchwith no matching case runs no branch, and the function returnsNone. ABCand@abstractmethodmake the missing method an error when the object is created, as the last test shows. Without them, the error would come only at the call toperimeter.
import java.util.List;
public class Main {
record Raw(String kind, double a, double b) {}
// Before: each method switches on the kind.
static double areaBefore(Raw s) {
switch (s.kind()) {
case "circle": return Math.PI * s.a() * s.a();
case "square": return s.a() * s.a();
case "triangle": return s.a() * s.b() / 2;
default: return 0;
}
}
static double perimeterBefore(Raw s) {
switch (s.kind()) {
case "circle": return 2 * Math.PI * s.a();
case "square": return 4 * s.a();
default: return 0; // the triangle case was never added
}
}
// After: a sealed interface, and a record for each kind.
sealed interface Shape permits Circle, Square, Triangle {
double area();
double perimeter();
}
record Circle(double r) implements Shape {
public double area() { return Math.PI * r * r; }
public double perimeter() { return 2 * Math.PI * r; }
}
record Square(double side) implements Shape {
public double area() { return side * side; }
public double perimeter() { return 4 * side; }
}
record Triangle(double a, double b, double c) implements Shape {
public double area() {
double s = (a + b + c) / 2;
return Math.sqrt(s * (s - a) * (s - b) * (s - c));
}
public double perimeter() { return a + b + c; }
}
// A switch over the sealed type must cover each case; it needs no default.
static String name(Shape s) {
return switch (s) {
case Circle c -> "circle";
case Square q -> "square";
case Triangle t -> "triangle";
};
}
static void check(boolean ok, String what) {
if (!ok) throw new AssertionError(what);
}
public static void main(String[] args) {
Raw t = new Raw("triangle", 3, 4);
check(areaBefore(t) == 6, "before area");
check(perimeterBefore(t) == 0, "before perimeter");
System.out.println("before: the perimeter of a triangle is 0");
List<Shape> shapes = List.of(new Circle(1), new Square(2), new Triangle(3, 4, 5));
check(shapes.get(0).perimeter() == 2 * Math.PI, "circle");
check(shapes.get(1).perimeter() == 8 && shapes.get(1).area() == 4, "square");
check(shapes.get(2).perimeter() == 12 && shapes.get(2).area() == 6, "triangle");
check(name(shapes.get(2)).equals("triangle"), "name");
System.out.println("after: tests pass");
}
}
before: the perimeter of a triangle is 0
after: tests pass
- A record that implements
Shapeand leaves outperimeterdoes not compile, so a kind that is added cannot be half done. - The
switchinnamehas nodefault. If a fourth record is added to thepermitslist, this switch stops compiling until it has a case for it.
package main
import (
"fmt"
"math"
)
type raw struct {
kind string
a, b float64
}
// Before: each function switches on the kind.
func areaBefore(s raw) float64 {
switch s.kind {
case "circle":
return math.Pi * s.a * s.a
case "square":
return s.a * s.a
case "triangle":
return s.a * s.b / 2
}
return 0
}
func perimeterBefore(s raw) float64 {
switch s.kind {
case "circle":
return 2 * math.Pi * s.a
case "square":
return 4 * s.a
}
return 0 // the triangle case was never added
}
// After: an interface, and a type for each kind.
type Shape interface {
Area() float64
Perimeter() float64
}
type Circle struct{ R float64 }
func (c Circle) Area() float64 { return math.Pi * c.R * c.R }
func (c Circle) Perimeter() float64 { return 2 * math.Pi * c.R }
type Square struct{ Side float64 }
func (q Square) Area() float64 { return q.Side * q.Side }
func (q Square) Perimeter() float64 { return 4 * q.Side }
type Triangle struct{ A, B, C float64 }
func (t Triangle) Area() float64 {
s := (t.A + t.B + t.C) / 2
return math.Sqrt(s * (s - t.A) * (s - t.B) * (s - t.C))
}
func (t Triangle) Perimeter() float64 { return t.A + t.B + t.C }
func check(ok bool, what string) {
if !ok {
panic(what)
}
}
func main() {
t := raw{"triangle", 3, 4}
check(areaBefore(t) == 6, "before area")
check(perimeterBefore(t) == 0, "before perimeter")
fmt.Println("before: the perimeter of a triangle is 0")
shapes := []Shape{Circle{1}, Square{2}, Triangle{3, 4, 5}}
want := []float64{2 * math.Pi, 8, 12}
for i, s := range shapes {
check(s.Perimeter() == want[i], fmt.Sprintf("perimeter %d", i))
}
check(shapes[2].Area() == 6, "triangle area")
fmt.Println("after: tests pass")
}
before: the perimeter of a triangle is 0
after: tests pass
- A type that has
Areabut notPerimeterdoes not satisfyShape, so the line that puts it in a[]Shapedoes not compile. - Go has no sealed interfaces, so a
switchon the type of aShapevalue is not checked for missing cases. The interface methods are the check.
Consequences
Each case is in one place, and a case that is added cannot be half done: a class that leaves out a method of the interface is a compile error in Java and Go, and an error at the call in JavaScript and Python. The code that uses the shapes no longer names the kinds.
The cost is the other direction of change. With classes, a kind that is added is one class, but an operation that is added is one method in each class. With switches, an operation that is added is one function, and a kind that is added is one case in each function. The right choice depends on which of the two changes more often. When the set of kinds is fixed and the operations grow, as in a compiler that walks a syntax tree, switches or the Visitor pattern can be the better design.
Some languages check switches for missing cases. In Java, a switch with patterns is an enhanced switch, and the language specification says that such a statement "must be exhaustive".6 Its example is a sealed interface with three permitted classes, where a switch with one case for each class needs no default.6 A switch over a sealed interface that leaves out a case does not compile. This keeps the switch form and removes the risk of a missed case, which is the real harm of the smell.
A single switch is not the smell. A factory that creates the right class from a string read from a file is often the one place where a switch on the kind belongs.
How to fix it
- The same switch on a type code in many functions: Replace Type Code with Subclasses, then Replace Conditional with Polymorphism.2
- Switches that only choose a value: a table from each case to its values.
- A fixed set of cases with growing operations: keep the switches, and use a language check for missing cases where one exists, such as an exhaustive switch over a sealed type in Java.6
- The switch that creates the objects: keep it, in one factory function.
Variants and related patterns
Shotgun Surgery. Repeated switches are a common cause: a case that is added needs an edit in each switch. See Shotgun Surgery.
Primitive Obsession. A type code stored as a string or an integer is the usual subject of the switches. See Primitive Obsession.
Strategy. A pattern that puts the variable behaviour in a separate object, chosen once. See Strategy pattern.
Visitor. A pattern for the opposite trade-off: a fixed set of kinds, and operations that grow. See Visitor pattern.
References
- Martin Fowler, Refactoring, Improving the Design of Existing Code, Addison-Wesley, 1999, Chapter 3, Bad Smells in Code, Switch Statements
- Martin Fowler, with Kent Beck, Refactoring, Improving the Design of Existing Code, second edition, Addison-Wesley, 2018, Chapter 3, Bad Smells in Code, Repeated Switches
- The Python Tutorial, More Control Flow Tools, Python 3.14, 4.7 match Statements
- The Go Programming Language Specification, Type switches
- Martin Fowler, Catalog of Refactorings, the cards Replace Conditional with Polymorphism and Replace Type Code with Subclasses
- The Java Language Specification, Java SE 25 Edition, Chapter 14, Blocks, Statements, and Patterns, 14.11.1.1 Exhaustive Switch Blocks and 14.11.2 The Switch Block of a switch Statement
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 0Q82CG Edit this page History Report an error Markdown