Video in progress
How do you plan moving a deep inheritance hierarchy that has grown over the years to composition in a large codebase?
First I find which axes the hierarchy varies along, pull each axis out into its own strategy object, write new classes through those, and move the old subclasses to an adapter one at a time. I don't do everything in one PR.
📖 Answer
The typical picture: AbstractReport -> AbstractPdfReport -> AbstractMonthlyPdfReport -> SalesMonthlyPdfReport. Each level expresses a different axis (format, period, content). When you need a new combination ("weekly Excel"), the number of classes grows as a product and code gets copied.
The plan:
- Separate the axes. In this example there are three independent dimensions: what (data source), when (period), how (format). Each one gets its own interface.
public final class Report {
private final DataSource data;
private final Period period;
private final Renderer renderer;
public byte[] build(LocalDate day) {
return renderer.render(data.load(period.rangeFor(day)));
}
}
- Build the new path alongside. New reports are built only through composition. Forbid adding new subclasses to the old hierarchy (an ArchUnit rule or
sealed). - Move the old classes. For each subclass: move the overridden methods to the matching strategy and the base class logic to the composition object. Before each move, a golden-file test: the old and the new report are identical byte for byte.
- Delete the base classes when they've been emptied out.
The organizational side:
- don't do the migration as background work; do it with every change ("move the class you're changing");
- a progress metric: how many subclasses are left;
- a new example for the team: a README and one clean sample.
Inheritance isn't bad across the board: with a real "is-a" relationship and a stable base class (for example, AbstractRoutingDataSource) it's convenient. The problem is when one hierarchy carries several independent dimensions.
Sign up to mark studied questions and save your progress.