Template Method

Defining an algorithm's skeleton in a base class and letting subclasses fill in steps — hooks, the Hollywood principle, framework examples, and replacing inheritance with composition.

Beginner 2 min readLesson 18 of 24

Intent: define the skeleton of an algorithm in a method, deferring some steps to subclasses. Subclasses redefine certain steps without changing the algorithm's structure.

Example: every data import does the same thing — open the source, read records, validate, transform, save, report — but reading CSV differs from reading JSON or an API.

  1. open() — abstract: each subclass knows its source
  2. read() — abstract
  3. validate(record) — hook: default accepts everything; subclasses may override
  4. transform(record) — abstract
  5. save(records) — fixed in the base class
  6. report() — fixed
public abstract class DataImporter {
    // The template method: final so subclasses can't change the sequence
    public final ImportReport run() {
        open();
        List<Record> valid = new ArrayList<>();
        int rejected = 0;
        for (RawRecord raw : read()) {
            if (validate(raw)) valid.add(transform(raw));
            else rejected++;
        }
        save(valid);
        close();
        return new ImportReport(valid.size(), rejected);
    }

    protected abstract void open();                               // required steps
    protected abstract Iterable<RawRecord> read();
    protected abstract Record transform(RawRecord raw);

    protected boolean validate(RawRecord raw) { return true; }    // hook: optional override
    protected void close() {}                                     // hook

    private void save(List<Record> records) { repository.saveAll(records); }  // fixed
}

public class CsvImporter extends DataImporter {
    private final Path path; private BufferedReader reader;
    public CsvImporter(Path path) { this.path = path; }
    protected void open() { reader = Files.newBufferedReader(path); }
    protected Iterable<RawRecord> read() { return () -> reader.lines().skip(1).map(RawRecord::fromCsv).iterator(); }
    protected Record transform(RawRecord r) { return new Record(r.get(0), Double.parseDouble(r.get(1))); }
    @Override protected boolean validate(RawRecord r) { return r.size() == 2; }
    @Override protected void close() { try { reader.close(); } catch (IOException ignored) {} }
}

The Hollywood principle

"Don't call us, we'll call you." The base class controls the flow and calls the subclass's steps — not the other way round. This inversion of control is the essence of frameworks:

FrameworkTemplateYou fill in
JUnit / pytestTest lifecyclesetUp, test method, tearDown
ServletsHttpServlet.service()doGet, doPost
React class componentsRender lifecyclerender, componentDidMount
Java collectionsAbstractListget(i) and size() — iteration, contains, etc. come free
AndroidActivity lifecycleonCreate, onResume
SpringJdbcTemplateA callback that maps rows

Template method vs strategy

The same goal — vary steps of an algorithm — with different mechanisms:

Template Method (inheritance)
  • Varying steps are overridden methods in subclasses
  • Chosen at compile time by picking a subclass
  • Simple when there's one natural axis of variation
  • Couples subclasses to the base class
Strategy / callbacks (composition)
  • Varying steps are objects or functions passed in
  • Can be swapped at runtime and mixed freely
  • Easier to test each piece in isolation
  • Modern APIs often prefer this: JdbcTemplate.query(sql, rowMapper)
Python
# Same importer with composition: steps are passed in
def run_import(read, transform, validate=lambda r: True):
    records = [transform(r) for r in read() if validate(r)]
    repository.save_all(records)
Key takeaways
  • Template Method fixes the algorithm's skeleton in a base class; subclasses fill in steps.
  • Abstract steps are required; hooks are optional overrides with defaults.
  • Make the template method final so the sequence can't be broken.
  • It's the Hollywood principle behind most frameworks.
  • Passing functions (strategy) is the composition-based alternative.