Video in progress
Template Method and Strategy often solve the same problem. When does an inheritance-based Template Method become a problem?
Template Method works through inheritance, Strategy through composition. When the hierarchy gets deep, subclasses become tied to the parent class's internal order, and combining two independently varying axes leads to a combinatorial explosion, and that's when you should move to Strategy.
📖 Answer
This happened in one project: AbstractImporter with the steps read(), validate(), save(). First came CsvImporter and ExcelImporter. Then "CSV without validation" was needed: LenientCsvImporter extends CsvImporter. Then "Excel, but into a different database": ArchiveExcelImporter. A year later there was a 4-level hierarchy, and who calls super.validate() and who doesn't, nobody knew for sure.
The problems:
- Two axes. The format (CSV/Excel) and the destination (main/archive database) vary independently. With inheritance every combination needs a class: 2×2 = 4, 3×3 = 9.
- A brittle parent class. If the order of steps in the parent changes or a new hook is added, all subclasses are silently affected.
- Testing. To test a single step on its own, you have to bring up the whole abstract class.
With Strategy:
public final class Importer {
private final RowReader reader;
private final RowValidator validator;
private final RowSink sink;
public Importer(RowReader reader, RowValidator validator, RowSink sink) { ... }
public ImportResult run(InputStream in) {
var rows = reader.read(in);
var valid = validator.filter(rows);
return sink.write(valid);
}
}
new Importer(new CsvReader(), RowValidator.none(), archiveSink);
Each part is swapped separately, and the combinations are assembled in the constructor call.
When Template Method is fine: the number of steps is small, there's a single axis of variation, and you want to strictly protect the skeleton (for example, framework code, AbstractList). As a rule: if super.xxx() calls start appearing in a subclass, that's a signal to move to composition.
Sign up to mark studied questions and save your progress.