Programming Search⌘K

Patterncore

Parallel Inheritance Hierarchies

Also called parallel hierarchies.

A code smell: two class hierarchies mirror each other, so each subclass added to one needs a matching subclass in the other, and the two must change together.

Family
code-smell
Intent
Find the hierarchies whose subclasses come in pairs, and move the behaviour of one into the other, so that one hierarchy is left.

Intent

Find two hierarchies whose subclasses come in pairs: Circle and CircleRenderer, Square and SquareRenderer. Each time someone adds a subclass to one, they must add its twin to the other. Move the behaviour of one hierarchy into the classes of the other, until the second hierarchy has nothing left and can be deleted.

Problem

The first edition of Refactoring names this smell and calls it a special case of Shotgun Surgery: each time a programmer makes a subclass of one class, they must also make a subclass of another. It gives a sign that is quick to check: the class names in one hierarchy have the same prefixes as the names in the other.1

The second edition does not list the smell on its own. The problem is still there, inside Shotgun Surgery: one change, one more kind of shape, forces edits in several classes.2

The forces are these:

  • Each hierarchy was a sensible split when it was made. Shapes know geometry, and renderers know a drawing format.
  • The pairs are linked by a convention, not by the compiler. A missing twin shows up at run time, often as a failed lookup in a table from one class to the other.
  • The two hierarchies change together, so a reader must keep both in mind to make any change.
  • Some parallel hierarchies are on purpose. When both sides vary on their own, the pairing is the design, and the fix is not to merge them.

Solution

The first edition gives the general strategy: make the instances of one hierarchy refer to the instances of the other, then use Move Method and Move Field until the hierarchy that refers disappears.1 The catalogue at refactoring.com has cards for both refactorings, and gives Move Method as another name for Move Function.3

  1. Link the pairs: give each object of one hierarchy a reference to its twin, or a method that finds it. The table that maps one class to the other is now in one place.
  2. Move the behaviour: Move Function for each method of the twin, into the class that it serves.
  3. Move the data: Move Field for each field of the twin.
  4. Delete the empty hierarchy.

Before merging, ask whether the two sides really vary together. If there are four shapes and three output formats, and each format must draw each shape, merging gives twelve methods spread over four classes, and a fifth format means editing every shape. The bridge pattern is the design for that case. Wikipedia describes it as a pattern meant to "decouple an abstraction from its implementation so that the two can vary independently".4 The Visitor pattern is another design for a fixed set of classes and a growing set of operations.

Example

Each shape has a renderer subclass that draws it as SVG, and a table maps each shape class to its renderer class. Adding a triangle needs a Triangle and a TriangleRenderer, and an entry in the table.

import assert from "node:assert/strict";

// Before: a shape hierarchy and a renderer hierarchy that mirrors it.
class CircleBefore { constructor(r) { this.r = r; } }
class SquareBefore { constructor(side) { this.side = side; } }
class TriangleBefore { constructor(base, height) { Object.assign(this, { base, height }); } }
class CircleRenderer { svg(c) { return `<circle r="${c.r}"/>`; } }
class SquareRenderer { svg(s) { return `<rect width="${s.side}" height="${s.side}"/>`; } }
const renderers = new Map([[CircleBefore, new CircleRenderer()], [SquareBefore, new SquareRenderer()]]);
function svgBefore(shape) {
  const renderer = renderers.get(shape.constructor);
  if (!renderer) throw new Error(`no renderer for ${shape.constructor.name}`);
  return renderer.svg(shape);
}

// After: each shape draws itself, and the renderer hierarchy is gone.
class Circle {
  constructor(r) { this.r = r; }
  svg() { return `<circle r="${this.r}"/>`; }
}
class Square {
  constructor(side) { this.side = side; }
  svg() { return `<rect width="${this.side}" height="${this.side}"/>`; }
}
class Triangle {
  constructor(base, height) { Object.assign(this, { base, height }); }
  svg() { return `<polygon points="0,${this.height} ${this.base},${this.height} ${this.base / 2},0"/>`; }
}

assert.equal(new Circle(5).svg(), svgBefore(new CircleBefore(5)));
assert.equal(new Square(4).svg(), svgBefore(new SquareBefore(4)));

// The twin is missing for the triangle, and only the run finds out.
assert.throws(() => svgBefore(new TriangleBefore(6, 3)), /no renderer for TriangleBefore/);
assert.equal(new Triangle(6, 3).svg(), '<polygon points="0,3 6,3 3,0"/>');
console.log("svg: tests pass");
Output
svg: tests pass

In the second version a triangle is one class, with no table to update. A programmer who adds it sees that every other shape has an svg method, and in a typed language an interface requires it.

Language What the example shows
JavaScript the renderer hierarchy moved into the shapes, as above
Python the same merge, with an abstract base class that requires svg
Java the same merge, with a sealed interface whose permits list names the shapes
Go the same merge, with an interface that each shape type satisfies
PythonGitHub
from abc import ABC, abstractmethod


# Before: a shape hierarchy and a renderer hierarchy that mirrors it.
class CircleBefore:
    def __init__(self, r):
        self.r = r


class SquareBefore:
    def __init__(self, side):
        self.side = side


class TriangleBefore:
    def __init__(self, base, height):
        self.base, self.height = base, height


class CircleRenderer:
    def svg(self, c):
        return f'<circle r="{c.r}"/>'


class SquareRenderer:
    def svg(self, s):
        return f'<rect width="{s.side}" height="{s.side}"/>'


RENDERERS = {CircleBefore: CircleRenderer(), SquareBefore: SquareRenderer()}


def svg_before(shape):
    try:
        return RENDERERS[type(shape)].svg(shape)
    except KeyError:
        raise LookupError(f"no renderer for {type(shape).__name__}") from None


# After: each shape draws itself, and the base class requires it.
class Shape(ABC):
    @abstractmethod
    def svg(self) -> str: ...


class Circle(Shape):
    def __init__(self, r):
        self.r = r

    def svg(self):
        return f'<circle r="{self.r}"/>'


class Square(Shape):
    def __init__(self, side):
        self.side = side

    def svg(self):
        return f'<rect width="{self.side}" height="{self.side}"/>'


class Triangle(Shape):
    def __init__(self, base, height):
        self.base, self.height = base, height

    def svg(self):
        return f'<polygon points="0,{self.height} {self.base},{self.height} {self.base / 2:g},0"/>'


assert Circle(5).svg() == svg_before(CircleBefore(5))
assert Square(4).svg() == svg_before(SquareBefore(4))
try:
    svg_before(TriangleBefore(6, 3))
    raise AssertionError("the missing twin must fail")
except LookupError as e:
    assert "TriangleBefore" in str(e)
assert Triangle(6, 3).svg() == '<polygon points="0,3 6,3 3,0"/>'


class Hexagon(Shape):  # forgot svg
    pass


try:
    Hexagon()
    raise AssertionError("an abstract method must block the instance")
except TypeError:
    pass
print("svg: tests pass")
Output
svg: tests pass
  • Shape is an abstract base class. A subclass that does not define svg cannot be instantiated, so the missing method is found when the object is made, not when it is drawn.
  • {self.base / 2:g} formats 3.0 as 3, so the output matches the JavaScript version.
JavaGitHub
import java.util.Map;

public class Main {
    // Before: a shape hierarchy and a renderer hierarchy that mirrors it.
    interface ShapeBefore {}
    record CircleBefore(int r) implements ShapeBefore {}
    record SquareBefore(int side) implements ShapeBefore {}
    record TriangleBefore(int base, int height) implements ShapeBefore {}

    interface Renderer { String svg(ShapeBefore s); }
    static final class CircleRenderer implements Renderer {
        public String svg(ShapeBefore s) { return "<circle r=\"" + ((CircleBefore) s).r() + "\"/>"; }
    }
    static final class SquareRenderer implements Renderer {
        public String svg(ShapeBefore s) {
            int side = ((SquareBefore) s).side();
            return "<rect width=\"" + side + "\" height=\"" + side + "\"/>";
        }
    }

    static final Map<Class<?>, Renderer> RENDERERS =
            Map.of(CircleBefore.class, new CircleRenderer(), SquareBefore.class, new SquareRenderer());

    static String svgBefore(ShapeBefore s) {
        Renderer r = RENDERERS.get(s.getClass());
        if (r == null) throw new IllegalStateException("no renderer for " + s.getClass().getSimpleName());
        return r.svg(s);
    }

    // After: each shape draws itself, and the sealed interface lists the shapes.
    sealed interface Shape permits Circle, Square, Triangle {
        String svg();
    }
    record Circle(int r) implements Shape {
        public String svg() { return "<circle r=\"" + r + "\"/>"; }
    }
    record Square(int side) implements Shape {
        public String svg() { return "<rect width=\"" + side + "\" height=\"" + side + "\"/>"; }
    }
    record Triangle(int base, int height) implements Shape {
        public String svg() {
            return "<polygon points=\"0," + height + " " + base + "," + height + " " + base / 2 + ",0\"/>";
        }
    }

    public static void main(String[] args) {
        if (!new Circle(5).svg().equals(svgBefore(new CircleBefore(5)))) throw new AssertionError("circle");
        if (!new Square(4).svg().equals(svgBefore(new SquareBefore(4)))) throw new AssertionError("square");
        try {
            svgBefore(new TriangleBefore(6, 3));
            throw new AssertionError("the missing twin must fail");
        } catch (IllegalStateException expected) {
        }
        if (!new Triangle(6, 3).svg().equals("<polygon points=\"0,3 6,3 3,0\"/>")) throw new AssertionError("triangle");
        System.out.println("svg: tests pass");
    }
}
Output
svg: tests pass
  • Each renderer in the first version must cast its argument to the shape it draws. The casts are a second sign that the two hierarchies belong together.
  • Shape is sealed and declares svg, so every permitted shape must implement it, and the compiler reports a missing one.
  • base / 2 is integer division in Java, which is correct here because the base is even.
package main

import (
	"fmt"
	"reflect"
)

// Before: shape types and renderer types that mirror them.
type circleBefore struct{ r int }
type squareBefore struct{ side int }
type triangleBefore struct{ base, height int }

type renderer interface{ svg(shape any) string }
type circleRenderer struct{}
type squareRenderer struct{}

func (circleRenderer) svg(s any) string { return fmt.Sprintf(`<circle r="%d"/>`, s.(circleBefore).r) }
func (squareRenderer) svg(s any) string {
	side := s.(squareBefore).side
	return fmt.Sprintf(`<rect width="%d" height="%d"/>`, side, side)
}

var renderers = map[reflect.Type]renderer{
	reflect.TypeFor[circleBefore](): circleRenderer{},
	reflect.TypeFor[squareBefore](): squareRenderer{},
}

func svgBefore(s any) (string, error) {
	r, ok := renderers[reflect.TypeOf(s)]
	if !ok {
		return "", fmt.Errorf("no renderer for %T", s)
	}
	return r.svg(s), nil
}

// After: each shape draws itself, and the interface names the method.
type shape interface{ svg() string }

type circle struct{ r int }
type square struct{ side int }
type triangle struct{ base, height int }

func (c circle) svg() string { return fmt.Sprintf(`<circle r="%d"/>`, c.r) }
func (s square) svg() string { return fmt.Sprintf(`<rect width="%d" height="%d"/>`, s.side, s.side) }
func (t triangle) svg() string {
	return fmt.Sprintf(`<polygon points="0,%d %d,%d %d,0"/>`, t.height, t.base, t.height, t.base/2)
}

// The compiler checks each shape here.
var _ = []shape{circle{}, square{}, triangle{}}

func main() {
	for _, pair := range []struct {
		after  shape
		before any
	}{{circle{5}, circleBefore{5}}, {square{4}, squareBefore{4}}} {
		got, err := svgBefore(pair.before)
		if err != nil || got != pair.after.svg() {
			panic(fmt.Sprint("mismatch: ", got, err))
		}
	}
	if _, err := svgBefore(triangleBefore{6, 3}); err == nil {
		panic("the missing twin must fail")
	}
	if (triangle{6, 3}).svg() != `<polygon points="0,3 6,3 3,0"/>` {
		panic("triangle")
	}
	fmt.Println("svg: tests pass")
}
Output
svg: tests pass
  • The table of the first version is keyed by reflect.Type, and each renderer asserts the type of its argument. Both are the price of linking two sets of types by convention.
  • The line var _ = []shape{circle{}, square{}, triangle{}} makes the compiler check that each shape type has an svg method. It is a common Go idiom for such checks.
  • reflect.TypeFor needs Go 1.22 or later.

Consequences

There is one hierarchy, and an added subclass is one class. The compiler or a base class can require each subclass to have the methods it needs, so a missing method is found before the program runs.

The merged classes know more. A shape now knows SVG, which mixes geometry with one output format. With one format that is a fair trade. With several formats that change for their own reasons, the merge produces Divergent Change in each shape, and the parallel hierarchies, or a bridge, were the better design.

The decision depends on which side grows. If shapes are added often and formats rarely, put the drawing in the shapes. If formats are added often and shapes rarely, keep a separate hierarchy per format, as a visitor does, and accept that an added shape touches each format.

How to fix it

  • Two hierarchies whose subclasses come in pairs: link each pair, then Move Function and Move Field from one side to the other, then delete the empty side.1
  • Two hierarchies that really vary on their own: keep them, and make the link explicit with a bridge. See Bridge pattern.4

Shotgun Surgery. The general smell: one change, many edits. Parallel hierarchies are the form it takes with inheritance. See Shotgun Surgery.

Bridge pattern. The design for two hierarchies that should vary on their own. See Bridge pattern.

Visitor pattern. A deliberate parallel structure: one class per operation, with one method per element class. See Visitor pattern.

References

  1. Martin Fowler, Refactoring, Improving the Design of Existing Code, Addison-Wesley, 1999, Chapter 3, Bad Smells in Code, Parallel Inheritance Hierarchies
  2. Martin Fowler, with Kent Beck, Refactoring, Improving the Design of Existing Code, second edition, Addison-Wesley, 2018, Chapter 3, Bad Smells in Code, Shotgun Surgery
  3. Martin Fowler, Catalog of Refactorings, the cards Move Function (alias Move Method) and Move Field
  4. Wikipedia, Bridge pattern, revision 1383733369, the introduction

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.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW4 complete
  • a review of the text: no review record reviews/R317YJ/text.yaml