SyntaxPilot
Courses/Low-Level Design/Lesson 38
Video coming soonThis lesson’s video is being made

Start with the notes below; the video appears here as soon as it is on YouTube.

Low-Level Design · Lesson 38 of 90

Template Method pattern

Template Method patterntemplate methodabstract stepsprimitive operationshook methodsHollywood principlefinal template methodtemplate method vs strategydata-import pipeline example

These are the notes for Low-Level Design (LLD) episode 38, the fifth behavioural pattern (patterns about how objects share work and talk to each other). The Template Method pattern puts the order of an algorithm's steps in one method of a base class, and lets subclasses fill in only the steps that differ. We start with a recipe card for chai and coffee, watch two copy-pasted importers give two different totals for the same data, and invent the pattern as the fix. Every program was actually run with javac Main.java && java -cp . Main (Java 21). Outputs are real.

1. The real-life idea: one recipe card, two drinks

In a kitchen In code
The recipe card: boil, brew, pour, extras, in this order The template method: a method that fixes the order of the steps
Boil water, pour into a cup: the same for every drink Shared steps: written once, in the base class
Brew: tea leaves for chai, ground coffee for coffee Abstract steps (primitive operations): each subclass fills them in
"Add sugar if you like" A hook: an optional step that does nothing unless you fill it in

2. The problem: copy-pasted importers

Every night, Asha's cafe imports the day's sales from two places:

  • CSV (comma-separated values) from the billing counter: one row per line, values separated by commas, with a header row on top. chai, 120
  • JSON (JavaScript Object Notation) from the delivery app: text with names and values in curly braces. {"amount": 120}

A bad row with a negative amount once broke the totals, so someone added "skip negative amounts" to the CSV importer. The JSON importer had been copy-pasted from it before that fix.

import java.util.*;
class CsvImporter {
    void importData(List<String> lines) {
        int total = 0;
        for (String line : lines.subList(1, lines.size())) {        // skip the header row
            int amount = Integer.parseInt(line.split(",")[1].trim());
            if (amount < 0) { System.out.println("  csv: skipped " + line); continue; }   // the fix
            total += amount;
        }
        System.out.println("  csv: saved total " + total);
    }
}
class JsonImporter {                                                // copy-pasted, then changed
    void importData(List<String> lines) {
        int total = 0;
        for (String line : lines) {
            int amount = Integer.parseInt(line.replaceAll("[^0-9-]", ""));
            total += amount;                                        // ...the fix never came here
        }
        System.out.println("  json: saved total " + total);
    }
}
public class Main {
    public static void main(String[] args) {
        new CsvImporter().importData(List.of("item,amount", "chai, 120", "dosa, -90", "samosa, 60"));
        new JsonImporter().importData(List.of("{\"amount\": 120}", "{\"amount\": -90}", "{\"amount\": 60}"));
    }
}
  csv: skipped dosa, -90
  csv: saved total 180
  json: saved total 90

Same data, two totals. No error, and the accounts are wrong by Rs 90.

Why it failed

  • Reading rows and parsing an amount really differ; checking, adding and saving are exactly the same.
  • Yet the whole algorithm exists twice, so a fix in one copy never reaches the other.
  • A third format (Excel) would mean a third copy. This is the DRY problem from episode 17: don't repeat yourself.
  • Like the recipe card: write the order once; let each format fill in only what differs.

3. The fix: the template method

import java.util.*;
abstract class DataImporter {
    final void importData(List<String> lines) {                     // the template method
        int total = 0;
        for (String line : rows(lines)) {
            int amount = parse(line);
            if (amount < 0) { System.out.println("  skipped " + line); continue; }   // written ONCE
            total += amount;
        }
        System.out.println("  " + getClass().getSimpleName() + ": saved " + total);
    }
    abstract List<String> rows(List<String> lines);                 // the steps that differ
    abstract int parse(String line);
}
class CsvImporter extends DataImporter {
    List<String> rows(List<String> lines) { return lines.subList(1, lines.size()); }
    int parse(String line) { return Integer.parseInt(line.split(",")[1].trim()); }
}
class JsonImporter extends DataImporter {
    List<String> rows(List<String> lines) { return lines; }
    int parse(String line) { return Integer.parseInt(line.replaceAll("[^0-9-]", "")); }
}
public class Main {
    public static void main(String[] args) {
        new CsvImporter().importData(List.of("item,amount", "chai, 120", "dosa, -90", "samosa, 60"));
        new JsonImporter().importData(List.of("{\"amount\": 120}", "{\"amount\": -90}", "{\"amount\": 60}"));
    }
}
  skipped dosa, -90
  CsvImporter: saved 180
  skipped {"amount": -90}
  JsonImporter: saved 180
  • DataImporter is an abstract class (episode 3): it can't be created with new, only extended, and it may declare abstract methods (methods with no body).
  • importData is the template method. It runs the steps in a fixed order and contains the negative check once. It is final, so no subclass can change the order (section 5 shows why).
  • rows and parse are the primitive operations: the abstract steps every subclass must fill in.
  • CsvImporter and JsonImporter now contain only what's different: two short methods each. The JSON importer got the fix without anyone touching it.

4. It has a name: the Template Method pattern

            +--------------------------------+
            | DataImporter «abstract class»  |
            | + importData()  {final}        |  <- template method (skeleton)
            | # rows()        {abstract}     |  <- primitive operations
            | # parse()       {abstract}     |
            | # afterSave()   {hook}         |  <- hook (empty by default)
            +--------------------------------+
                     ^                 ^
         +-----------------+   +-----------------+
         | CsvImporter     |   | JsonImporter    |
         | rows(), parse() |   | rows(), parse() |
         | afterSave()     |   |                 |
         +-----------------+   +-----------------+

The classic intent (SourceMaking): "Define the skeleton of an algorithm in an operation, deferring some steps to client subclasses. Template Method lets subclasses redefine certain steps of an algorithm without changing the algorithm's structure."

The Hollywood principle. Normally your code calls a library. Here the base class calls your methods, when it decides to. SourceMaking: "This inverted control structure has been affectionately labelled "the Hollywood principle" - "don't call us, we'll call you"." It is a form of inversion of control (episode 16).

In the JDK. java.util.AbstractList: "To implement an unmodifiable list, the programmer needs only to extend this class" and write get(int) and size(). Methods such as contains, indexOf and iteration are built on top of those two.

Part In our example Must a subclass write it?
Template method importData() No, and it can't: it's final
Primitive operation (abstract step) rows(), parse() Yes
Hook afterSave() Optional
Concrete (shared) step the negative check, the total No: written once in the base class

5. The trap: a template that isn't final

import java.util.*;
abstract class DataImporter {
    void importData(List<String> lines) {                           // NOT final
        int total = 0;
        for (String line : rows(lines)) {
            int amount = parse(line);
            if (amount < 0) { System.out.println("  skipped " + line); continue; }   // written ONCE
            total += amount;
        }
        System.out.println("  " + getClass().getSimpleName() + ": saved " + total);
    }
    abstract List<String> rows(List<String> lines);                 // the steps that differ
    abstract int parse(String line);
}
class JsonImporter extends DataImporter {
    List<String> rows(List<String> lines) { return lines; }
    int parse(String line) { return Integer.parseInt(line.replaceAll("[^0-9-]", "")); }
    void importData(List<String> lines) {                           // "faster": my own loop
        int total = 0; for (String l : lines) total += parse(l);
        System.out.println("  JsonImporter: saved " + total);
    }
}
public class Main {
    public static void main(String[] args) {
        new JsonImporter().importData(List.of("{\"amount\": 120}", "{\"amount\": -90}", "{\"amount\": 60}"));
    }
}
  JsonImporter: saved 90

The override replaced the whole skeleton, and the negative check went with it. Mark the template final:

import java.util.*;
abstract class DataImporter {
    final void importData(List<String> lines) {                     // final again
        int total = 0;
        for (String line : rows(lines)) {
            int amount = parse(line);
            if (amount < 0) { System.out.println("  skipped " + line); continue; }   // written ONCE
            total += amount;
        }
        System.out.println("  " + getClass().getSimpleName() + ": saved " + total);
    }
    abstract List<String> rows(List<String> lines);                 // the steps that differ
    abstract int parse(String line);
}
class JsonImporter extends DataImporter {
    List<String> rows(List<String> lines) { return lines; }
    int parse(String line) { return Integer.parseInt(line.replaceAll("[^0-9-]", "")); }
    void importData(List<String> lines) {                           // "faster": my own loop
        int total = 0; for (String l : lines) total += parse(l);
        System.out.println("  JsonImporter: saved " + total);
    }
}
public class Main {
    public static void main(String[] args) {
        new JsonImporter().importData(List.of("{\"amount\": 120}", "{\"amount\": -90}", "{\"amount\": 60}"));
    }
}
Main.java:18: error: importData(List<String>) in JsonImporter cannot override importData(List<String>) in DataImporter
    void importData(List<String> lines) {                           // "faster": my own loop
         ^
  overridden method is final
1 error

A final method cannot be overridden. Subclasses may change the steps, never the order.

6. Hook methods

Asha wants a message with the day's total, but only for the counter's CSV import. An abstract method would force every importer to write it. A hook is a normal method with an empty (or default) body that the template calls at a fixed point:

import java.util.*;
abstract class DataImporter {
    final void importData(List<String> lines) {                     // the template method
        int total = 0;
        for (String line : rows(lines)) { int a = parse(line); if (a >= 0) total += a; }   // same steps
        System.out.println("  " + getClass().getSimpleName() + ": saved " + total);
        afterSave(total);                                           // the hook
    }
    abstract List<String> rows(List<String> lines);                 // primitive operations
    abstract int parse(String line);
    void afterSave(int total) { }                                   // hook: does nothing by default
}
class CsvImporter extends DataImporter {
    List<String> rows(List<String> lines) { return lines.subList(1, lines.size()); }
    int parse(String line) { return Integer.parseInt(line.split(",")[1].trim()); }
    void afterSave(int total) { System.out.println("  message to Asha: today's sales Rs " + total); }
}
class JsonImporter extends DataImporter {                           // no afterSave: nothing extra
    List<String> rows(List<String> lines) { return lines; }
    int parse(String line) { return Integer.parseInt(line.replaceAll("[^0-9-]", "")); }
}
public class Main {
    public static void main(String[] args) {
        new CsvImporter().importData(List.of("item,amount", "chai, 120", "samosa, 60"));
        new JsonImporter().importData(List.of("{\"amount\": 120}", "{\"amount\": 60}"));
    }
}
  CsvImporter: saved 180
  message to Asha: today's sales Rs 180
  JsonImporter: saved 180

Abstract step = must; hook = may. Choose carefully which is which.

7. Template Method vs Strategy

The same job with composition instead of inheritance: one Importer class that receives the differing steps as objects.

  • Function<T, R>: takes a T, returns an R. Here: lines in, data rows out.
  • ToIntFunction<T>: takes a T, returns an int. Here: a row in, the amount out.
  • Both are functional interfaces (one abstract method), so we pass lambdas (episode 5).
import java.util.*;
import java.util.function.*;

class Importer {                                                    // ONE class, steps passed in
    private final Function<List<String>, List<String>> rows;
    private final ToIntFunction<String> parse;
    Importer(Function<List<String>, List<String>> rows, ToIntFunction<String> parse) {
        this.rows = rows; this.parse = parse;
    }
    void importData(String name, List<String> lines) {
        int total = 0;
        for (String line : rows.apply(lines)) {
            int amount = parse.applyAsInt(line);
            if (amount >= 0) total += amount;
        }
        System.out.println("  " + name + ": saved " + total);
    }
}
public class Main {
    public static void main(String[] args) {
        Importer csv = new Importer(l -> l.subList(1, l.size()),
                                    s -> Integer.parseInt(s.split(",")[1].trim()));
        Importer json = new Importer(l -> l,
                                     s -> Integer.parseInt(s.replaceAll("[^0-9-]", "")));
        csv.importData("csv", List.of("item,amount", "chai, 120", "dosa, -90", "samosa, 60"));
        json.importData("json", List.of("{\"amount\": 120}", "{\"amount\": -90}", "{\"amount\": 60}"));
    }
}
  csv: saved 180
  json: saved 180

This is really the Strategy pattern (episode 34): the steps are strategies plugged into one object.

Template Method Strategy
Mechanism Inheritance Composition
Steps chosen When you write the subclass (compile time) When you build the object; can swap at runtime
Classes One subclass per variant One class + small step objects or lambdas
Best when Several classes share one algorithm with a few varying steps You need to mix steps, or change them while running

Watch out: a template with many abstract steps makes every subclass painful. When in doubt, prefer composition (episode 11).

8. Template Method in the JDK: AbstractList

We fill in exactly two steps, get(int) and size(); AbstractList's own methods call them.

import java.util.*;

class Menu extends AbstractList<String> {                // the JDK's template
    private final String[] items = {"chai", "dosa", "samosa"};
    public String get(int i) { return items[i]; }        // step 1 we fill in
    public int size() { return items.length; }           // step 2 we fill in
}
public class Main {
    public static void main(String[] args) {
        List<String> menu = new Menu();
        System.out.println("contains dosa? " + menu.contains("dosa"));   // we never wrote contains
        System.out.println("index of samosa: " + menu.indexOf("samosa"));
        for (String item : menu) System.out.println("  - " + item);      // nor an iterator
        System.out.println(menu);                                        // nor toString
        menu.add("vada");                                                // nor add...
    }
}
contains dosa? true
index of samosa: 2
  - chai
  - dosa
  - samosa
[chai, dosa, samosa]
Exception in thread "main" java.lang.UnsupportedOperationException
    at java.base/java.util.AbstractList.add(AbstractList.java:155)
    at java.base/java.util.AbstractList.add(AbstractList.java:113)
    at Main.main(Main.java:15)

contains, indexOf, the for-each loop and toString all came from AbstractList, built on our two methods: don't call us, we'll call you. add throws UnsupportedOperationException because that's AbstractList's default for a step we didn't fill in: the list is read-only. Overriding add(int, E) (and set, remove) would make it changeable, like overriding a hook.

Common mistakes

Mistake What you see Why Fix
Copy-pasting the algorithm No error: json: saved total 90 A fix reached one copy only One template method
Template method not final No error: JsonImporter: saved 90 A subclass replaced the skeleton final. Compiler: importData(List<String>) in JsonImporter cannot override importData(List<String>) in DataImporter / overridden method is final
Every step abstract Subclasses full of empty methods Optional steps forced on everyone Hooks for optional steps
Calling a step from the base constructor Subclass fields still null or 0 The subclass part isn't initialised yet Call the template after construction (see practice 2)
Template method public but steps public too Callers run steps out of order Steps exposed Make steps protected or package-private

Mini project: the recipe card in code

abstract class HotDrink {
    final void make() {                                     // the template method
        boilWater();
        brew();                                             // primitive operation
        pour();
        if (wantsExtras()) addExtras();                     // hook + optional step
    }
    private void boilWater() { System.out.println("  boil water"); }
    private void pour()      { System.out.println("  pour into a cup"); }
    abstract void brew();
    boolean wantsExtras() { return true; }                  // hook with a default
    void addExtras() { }                                    // hook: empty by default
}
class Chai extends HotDrink {
    void brew()      { System.out.println("  brew tea leaves with ginger and milk"); }
    void addExtras() { System.out.println("  add sugar"); }
}
class BlackCoffee extends HotDrink {
    void brew()           { System.out.println("  brew ground coffee"); }
    boolean wantsExtras() { return false; }                 // no extras, please
}
public class Main {
    public static void main(String[] args) {
        System.out.println("chai:");         new Chai().make();
        System.out.println("black coffee:"); new BlackCoffee().make();
    }
}
chai:
  boil water
  brew tea leaves with ginger and milk
  pour into a cup
  add sugar
black coffee:
  boil water
  brew ground coffee
  pour into a cup

wantsExtras() is a hook that returns a value and lets a subclass switch an optional step off; addExtras() is a hook with an empty body. boilWater() and pour() are private: subclasses can't change them at all.

Practice

1. Add an ExcelImporter that reads tab-separated rows, plus a hook beforeRead(file) that logs the file name.

Answer
import java.util.*;

abstract class DataImporter {
    final void importData(String file, List<String> lines) {
        beforeRead(file);                                   // hook
        int total = 0;
        for (String line : rows(lines)) { int a = parse(line); if (a >= 0) total += a; }
        System.out.println("  " + getClass().getSimpleName() + ": saved " + total);
    }
    void beforeRead(String file) { }                        // hook: empty by default
    abstract List<String> rows(List<String> lines);
    abstract int parse(String line);
}
class ExcelImporter extends DataImporter {                  // tab-separated rows, header on top
    void beforeRead(String file) { System.out.println("  reading " + file); }
    List<String> rows(List<String> lines) { return lines.subList(1, lines.size()); }
    int parse(String line) { return Integer.parseInt(line.split("\t")[1].trim()); }
}
public class Main {
    public static void main(String[] args) {
        new ExcelImporter().importData("sales.tsv", List.of("item\tamount", "vada pav\t40", "lassi\t-5", "idli\t70"));
    }
}
  reading sales.tsv
  ExcelImporter: saved 110

\t is the tab character. The negative lassi row is skipped by the shared template; ExcelImporter didn't have to know about that rule.

2. Why is it dangerous to call an abstract step from the base class constructor? Show it.

Answer
abstract class Base {
    Base() { describe(); }                                  // calls a step from the constructor
    abstract void describe();
}
class Child extends Base {
    private String name = "Asha";
    void describe() { System.out.println("name = " + name); }
}
public class Main {
    public static void main(String[] args) {
        Child c = new Child();
        c.describe();
    }
}
name = null
name = Asha

Java runs the Base constructor before Child's field initialisers, so during that first call name is still null. Call the template method after the object is fully built.

3. Rewrite ExcelImporter with the lambda-based Importer from section 7.

Answer

Importer excel = new Importer(l -> l.subList(1, l.size()), s -> Integer.parseInt(s.split("\t")[1].trim())); then excel.importData("excel", lines);. No new class is needed.

Quick quiz

abstract class Report {
    final void print() {
        header(); body(); footer();
    }
    abstract void header();
    abstract void body();
    void footer() { }
}

Which method is the hook? (a) print() (b) header() (c) body() (d) footer()

Answer

(d) footer(). print() is the template method; header() and body() are primitive operations every subclass must write; footer() has an empty body that a subclass may override.

Interview questions

  1. What is the Template Method pattern? A behavioural pattern where a base class defines an algorithm's skeleton in one method and lets subclasses supply some steps.
  2. What are primitive operations and hooks? Primitive operations are abstract steps subclasses must implement; hooks are optional steps with a default (often empty) body.
  3. Why make the template method final? So subclasses can't change the order or skip shared steps such as validation.
  4. What is the Hollywood principle? "Don't call us, we'll call you": the framework or base class calls your code, not the other way around.
  5. Template Method vs Strategy? Inheritance vs composition; steps fixed per subclass vs steps passed in and swappable.
  6. Examples in Java? AbstractList (get, size), AbstractMap, InputStream subclasses implementing read(), and test frameworks that run setup, the test, then teardown in a fixed order.
  7. Downsides? Tight coupling through inheritance; one subclass per variant; many abstract steps make subclasses painful; Liskov issues if subclasses misuse hooks.
  8. How does it relate to DRY and OCP? The algorithm exists once (DRY); new variants are new subclasses (open for extension) without changing the template (closed for modification).
  9. Can a step be private? Yes, fixed shared steps can be private in the base class; only overridable steps are protected/package-private or abstract.
  10. Why not call steps from a constructor? Subclass fields aren't initialised yet.

Glossary

Term Meaning, with an example
Behavioural pattern A pattern about how objects share work and communicate
Template Method pattern A base class fixes an algorithm's steps; subclasses fill in some of them. DataImporter
Template method The method that runs the steps in a fixed order. importData()
Skeleton (of an algorithm) The fixed order of steps, without the details
Abstract class A class that can't be created with new, only extended; may have abstract methods
Abstract method A method with no body that subclasses must implement. abstract int parse(String line);
Abstract steps The steps a subclass must fill in
Primitive operations Another name for the abstract steps called by the template method
Hook method An optional step with a default (often empty) body. void afterSave(int total) { }
Hollywood principle "Don't call us, we'll call you": the base class calls your methods
Inversion of control The framework/base class controls the flow and calls your code (episode 16)
final method A method no subclass can override
Final template method A template method marked final, so the order can't change
Data-import pipeline Read rows → parse → validate → total → save
CSV Comma-separated values: one row per line. chai, 120
JSON Text with names and values in braces. {"amount": 120}
DRY Don't repeat yourself: one piece of knowledge, one place (episode 17)
Composition Building an object from other objects it holds (episode 11)
Function<T, R> A functional interface: takes T, returns R
ToIntFunction<T> A functional interface: takes T, returns an int
Lambda A short way to write a one-method interface. s -> Integer.parseInt(s)
Strategy One algorithm per object, passed in and swappable (episode 34)
Template Method vs Strategy Inheritance with fixed steps vs composition with swappable steps
AbstractList A JDK base class: implement get and size, get a full read-only list

Summary

  • Two copies of one algorithm drift apart: a fix reached the CSV importer only.
  • Template Method: a base-class method fixes the order of steps; subclasses fill in primitive operations and may override hooks.
  • Make the template method final, so the skeleton and shared checks can't be skipped.
  • Hollywood principle: don't call us, we'll call you.
  • Template Method vs Strategy: inheritance vs composition; prefer Strategy when steps must be mixed or swapped at runtime.

Next episode: The Chain of Responsibility: pass a request along a chain of handlers until one of them handles it.