Template Method Pattern
Two classes do almost the same job. They read input, loop over it, check each item, collect results and report, and they differ in one or two lines in the middle. Over time someone fixes a bug in one and forgets the other, and the "same" algorithm quietly drifts apart. Template Method stops that drift: the base class owns the sequence of steps, and subclasses supply only the steps that genuinely differ.
It is the most inheritance-heavy of the behavioral patterns, which makes it both easy to understand and easy to overuse. This page goes deeper than the behavioral patterns overview: a complete importer in three languages, the difference between abstract steps and hooks, a constructor trap that catches experienced Java developers, and a clear rule for when to replace the whole thing with a function parameter.
Intent
Define the skeleton of an algorithm in one method, and let subclasses redefine certain steps without changing the order or the overall structure.
The method that holds the skeleton is the template method. It is usually public and, where the language allows it, final. It calls a series of smaller methods:
- Abstract steps (also called primitive operations): every subclass must provide them, because there is no sensible default.
- Hooks: steps with a default, often empty, that subclasses may override to extend behaviour at a specific point.
- Invariant steps: private methods in the base class that no subclass can change, such as validation rules that must apply everywhere.
The control flow is inverted compared with ordinary inheritance. The subclass doesn't call the parent's code when it wants to; the parent calls the subclass's code at the moments it chooses. This is often summarised as the Hollywood principle: "don't call us, we'll call you".
The problem
A finance app imports bank statements. The first bank sends CSV with a header row. A second bank sends a fixed-width text file. Two developers wrote two importers.
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
record Transaction(String date, String description, long amountCents) {}
class CsvStatementImporter {
List<Transaction> importText(String text) {
List<Transaction> out = new ArrayList<>();
List<String> lines = text.lines().toList();
for (String line : lines.subList(1, lines.size())) { // skip the header
if (line.isBlank()) continue;
String[] f = line.split(",");
long cents = new BigDecimal(f[2].trim()).movePointRight(2).longValueExact();
if (cents == 0) continue; // business rule: drop zero rows
out.add(new Transaction(f[0].trim(), f[1].trim(), cents));
}
return out;
}
}
class FixedWidthStatementImporter {
List<Transaction> importText(String text) {
List<Transaction> out = new ArrayList<>();
for (String line : text.lines().toList()) {
String date = line.substring(0, 10); // a blank line throws here
String description = line.substring(10, 30).trim();
long cents = Long.parseLong(line.substring(30).trim());
out.add(new Transaction(date, description, cents)); // zero rows slip through
}
return out;
}
}
Each class is short and each looks fine on its own. Put them side by side and the problems show:
- The algorithm is duplicated. Both split the text into lines, loop, parse, filter and collect. Only the parsing of one line genuinely differs.
- The copies have already drifted. The CSV importer skips blank lines and drops zero-amount rows; the fixed-width one does neither. A product rule ("zero rows are noise") lives in only one place.
- One bad row aborts the whole import. Neither copy handles a malformed line gracefully. Fixing that means changing both, and the third bank's importer next month, and hoping nobody misses one.
- There is no single place for cross-cutting steps. If compliance asks for an audit record after every import, it gets pasted into every class.
What we want is one place that says "split into lines, skip headers and blanks, parse each line, validate, collect failures, then run any post-import step", and small classes that say only "here is how my bank's line format turns into a Transaction".
Structure
classDiagram
class StatementImporter {
<<abstract>>
+importText(text) ImportResult
#parse(line) Transaction*
#headerLines() int
#afterImport(accepted) void
-validate(tx) void
}
class CsvStatementImporter {
#parse(line) Transaction
#headerLines() int
}
class FixedWidthStatementImporter {
+auditLog: List
#parse(line) Transaction
#afterImport(accepted) void
}
class ImportResult {
+accepted: List
+rejected: List
}
StatementImporter <|-- CsvStatementImporter
StatementImporter <|-- FixedWidthStatementImporter
StatementImporter ..> ImportResult : returns
importText is the template method: public, final, and the only entry point. parse is abstract. headerLines and afterImport are hooks with defaults (zero header lines, do nothing). validate is private, so no subclass can weaken the rules.
Participants
| Participant | In the example | Responsibility |
|---|---|---|
| Abstract class | StatementImporter | Owns the template method and the invariant steps. Declares the abstract steps and the hooks, and decides when each one runs. |
| Template method | importText | The fixed algorithm. Final where the language allows, so subclasses can't reorder or skip steps. |
| Abstract steps | parse | The variation every subclass must supply. |
| Hooks | headerLines, afterImport | Optional extension points with safe defaults. |
| Concrete classes | CsvStatementImporter, FixedWidthStatementImporter | Fill in the steps for one variant, and nothing else. |
A good template method has few abstract steps (one to three) and few hooks. Each extra step is another thing every subclass author must understand, and another place where the base class and its subclasses are coupled.
Implementation
Each version below keeps the base class in charge of splitting, skipping, error handling, validation and the post-import hook. Subclasses parse a single line. A malformed row is rejected with a reason instead of aborting the import.
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
public class ImportDemo {
public static void main(String[] args) {
String csv = """
date,description,amount
2026-11-01,Coffee,-3.50
2026-11-02,Salary,2500.00
2026-11-03,Refund,abc
2026-11-04,Adjustment,0.00
""";
ImportResult r = new CsvStatementImporter().importText(csv);
assert r.accepted().size() == 2 : r;
assert r.accepted().get(0).amountCents() == -350;
assert r.rejected().size() == 2 : r;
String fixed = String.format("%-10s%-20s%d%n%n%-10s%-20s%d%n",
"2026-11-05", "Groceries", -4210, "2026-11-06", "Rent", -120000);
FixedWidthStatementImporter fw = new FixedWidthStatementImporter();
ImportResult f = fw.importText(fixed);
assert f.accepted().size() == 2 && f.rejected().isEmpty() : f;
assert f.accepted().get(1).description().equals("Rent");
assert fw.auditLog.equals(List.of("imported 2 rows, total -124210"));
System.out.println("template method: all assertions passed");
}
}
record Transaction(String date, String description, long amountCents) {}
record ImportResult(List<Transaction> accepted, List<String> rejected) {}
abstract class StatementImporter {
// The template method: final, so the order of steps cannot change.
public final ImportResult importText(String text) {
List<Transaction> accepted = new ArrayList<>();
List<String> rejected = new ArrayList<>();
List<String> lines = text.lines().filter(l -> !l.isBlank()).toList();
for (String line : lines.subList(Math.min(headerLines(), lines.size()), lines.size())) {
try {
Transaction tx = parse(line);
validate(tx);
accepted.add(tx);
} catch (IllegalArgumentException | ArithmeticException e) {
rejected.add(line + " -> " + e.getMessage());
}
}
afterImport(accepted);
return new ImportResult(List.copyOf(accepted), List.copyOf(rejected));
}
// Abstract step: every format must say how one line becomes a Transaction.
protected abstract Transaction parse(String line);
// Hooks: safe defaults that subclasses may override.
protected int headerLines() { return 0; }
protected void afterImport(List<Transaction> accepted) {}
// Invariant step: private, so no subclass can weaken it.
private void validate(Transaction tx) {
if (tx.description().isBlank()) throw new IllegalArgumentException("missing description");
if (tx.amountCents() == 0) throw new IllegalArgumentException("zero amount");
}
}
final class CsvStatementImporter extends StatementImporter {
@Override protected int headerLines() { return 1; }
@Override protected Transaction parse(String line) {
String[] f = line.split(",", -1);
if (f.length != 3) throw new IllegalArgumentException("expected 3 fields, got " + f.length);
long cents = new BigDecimal(f[2].trim()).movePointRight(2).longValueExact();
return new Transaction(f[0].trim(), f[1].trim(), cents);
}
}
final class FixedWidthStatementImporter extends StatementImporter {
final List<String> auditLog = new ArrayList<>();
@Override protected Transaction parse(String line) {
if (line.length() < 31) throw new IllegalArgumentException("line too short");
return new Transaction(line.substring(0, 10), line.substring(10, 30).trim(),
Long.parseLong(line.substring(30).trim()));
}
@Override protected void afterImport(List<Transaction> accepted) {
long total = accepted.stream().mapToLong(Transaction::amountCents).sum();
auditLog.add("imported " + accepted.size() + " rows, total " + total);
}
}
from abc import ABC, abstractmethod
from dataclasses import dataclass, field
from decimal import Decimal, InvalidOperation
from typing import final
@dataclass(frozen=True)
class Transaction:
date: str
description: str
amount_cents: int
@dataclass
class ImportResult:
accepted: list[Transaction] = field(default_factory=list)
rejected: list[str] = field(default_factory=list)
def to_cents(raw: str) -> int:
try:
cents = Decimal(raw.strip()) * 100
except InvalidOperation:
raise ValueError(f"bad amount {raw!r}") from None
if cents != cents.to_integral_value():
raise ValueError(f"more than two decimals in {raw!r}")
return int(cents)
class StatementImporter(ABC):
@final # checked by type checkers such as mypy, not at run time
def import_text(self, text: str) -> ImportResult:
result = ImportResult()
lines = [line for line in text.splitlines() if line.strip()]
for line in lines[self.header_lines():]:
try:
tx = self.parse(line)
self._validate(tx)
except ValueError as e:
result.rejected.append(f"{line} -> {e}")
else:
result.accepted.append(tx)
self.after_import(result.accepted)
return result
@abstractmethod
def parse(self, line: str) -> Transaction: ...
def header_lines(self) -> int: # hook
return 0
def after_import(self, accepted: list[Transaction]) -> None: # hook
pass
@staticmethod
def _validate(tx: Transaction) -> None: # invariant step
if not tx.description:
raise ValueError("missing description")
if tx.amount_cents == 0:
raise ValueError("zero amount")
class CsvStatementImporter(StatementImporter):
def header_lines(self) -> int:
return 1
def parse(self, line: str) -> Transaction:
fields = line.split(",")
if len(fields) != 3:
raise ValueError(f"expected 3 fields, got {len(fields)}")
date, description, amount = (f.strip() for f in fields)
return Transaction(date, description, to_cents(amount))
class FixedWidthStatementImporter(StatementImporter):
def __init__(self) -> None:
self.audit_log: list[str] = []
def parse(self, line: str) -> Transaction:
if len(line) < 31:
raise ValueError("line too short")
return Transaction(line[:10], line[10:30].strip(), int(line[30:]))
def after_import(self, accepted: list[Transaction]) -> None:
total = sum(t.amount_cents for t in accepted)
self.audit_log.append(f"imported {len(accepted)} rows, total {total}")
if __name__ == "__main__":
csv = """date,description,amount
2026-11-01,Coffee,-3.50
2026-11-02,Salary,2500.00
2026-11-03,Refund,abc
2026-11-04,Adjustment,0.00
"""
r = CsvStatementImporter().import_text(csv)
assert [t.amount_cents for t in r.accepted] == [-350, 250000]
assert len(r.rejected) == 2 and "bad amount" in r.rejected[0]
fixed = f"{'2026-11-05':<10}{'Groceries':<20}-4210\n\n{'2026-11-06':<10}{'Rent':<20}-120000\n"
fw = FixedWidthStatementImporter()
f = fw.import_text(fixed)
assert len(f.accepted) == 2 and not f.rejected
assert fw.audit_log == ["imported 2 rows, total -124210"]
try:
StatementImporter() # type: ignore[abstract]
raise AssertionError("abstract class must not be instantiable")
except TypeError:
pass
print("template method: all assertions passed")
type Transaction = { date: string; description: string; amountCents: number };
type ImportResult = { accepted: Transaction[]; rejected: string[] };
class ImportError extends Error {}
function toCents(raw: string): number {
const m = /^(-?)(\d+)(?:\.(\d{1,2}))?$/.exec(raw.trim());
if (!m) throw new ImportError(`bad amount "${raw}"`);
const cents = Number(m[2]) * 100 + Number((m[3] ?? "").padEnd(2, "0"));
return m[1] ? -cents : cents;
}
abstract class StatementImporter {
// TypeScript has no `final`; by convention, subclasses never override importText.
importText(text: string): ImportResult {
const result: ImportResult = { accepted: [], rejected: [] };
const lines = text.split(/\r?\n/).filter((l) => l.trim() !== "");
for (const line of lines.slice(this.headerLines())) {
try {
const tx = this.parse(line);
this.validate(tx);
result.accepted.push(tx);
} catch (e) {
if (!(e instanceof ImportError)) throw e; // real bugs still surface
result.rejected.push(`${line} -> ${e.message}`);
}
}
this.afterImport(result.accepted);
return result;
}
protected abstract parse(line: string): Transaction;
protected headerLines(): number {
return 0;
}
protected afterImport(_accepted: Transaction[]): void {}
private validate(tx: Transaction): void {
if (tx.description === "") throw new ImportError("missing description");
if (tx.amountCents === 0) throw new ImportError("zero amount");
}
}
class CsvStatementImporter extends StatementImporter {
protected override headerLines(): number {
return 1;
}
protected override parse(line: string): Transaction {
const fields = line.split(",").map((f) => f.trim());
if (fields.length !== 3) throw new ImportError(`expected 3 fields, got ${fields.length}`);
const [date, description, amount] = fields as [string, string, string];
return { date, description, amountCents: toCents(amount) };
}
}
class FixedWidthStatementImporter extends StatementImporter {
readonly auditLog: string[] = [];
protected override parse(line: string): Transaction {
if (line.length < 31) throw new ImportError("line too short");
const amountCents = Number(line.slice(30).trim()); // this format stores whole cents
if (!Number.isInteger(amountCents)) throw new ImportError("bad amount");
return { date: line.slice(0, 10), description: line.slice(10, 30).trim(), amountCents };
}
protected override afterImport(accepted: Transaction[]): void {
const total = accepted.reduce((sum, t) => sum + t.amountCents, 0);
this.auditLog.push(`imported ${accepted.length} rows, total ${total}`);
}
}
function assert(cond: boolean, msg = "assertion failed"): void {
if (!cond) throw new Error(msg);
}
const csv = [
"date,description,amount",
"2026-11-01,Coffee,-3.50",
"2026-11-02,Salary,2500.00",
"2026-11-03,Refund,abc",
"2026-11-04,Adjustment,0.00",
].join("\n");
const r = new CsvStatementImporter().importText(csv);
assert(r.accepted.map((t) => t.amountCents).join() === "-350,250000");
assert(r.rejected.length === 2);
const row = (d: string, desc: string, cents: number) => d.padEnd(10) + desc.padEnd(20) + cents;
const fw = new FixedWidthStatementImporter();
const f = fw.importText([row("2026-11-05", "Groceries", -4210), "", row("2026-11-06", "Rent", -120000)].join("\n"));
assert(f.accepted.length === 2 && f.rejected.length === 0);
assert(fw.auditLog[0] === "imported 2 rows, total -124210");
console.log("template method: all assertions passed");
Walking through the design
The base class owns everything that must be the same. Blank-line handling, header skipping, error collection, validation and the post-import hook are written once. When the third bank arrives, its importer is a dozen lines of parsing, and it gets correct error handling for free.
Subclasses can't break the algorithm. In Java importText is final and validate is private. A subclass can't skip validation, reorder steps, or forget to call the hook. Python's @final and TypeScript's lack of final give weaker guarantees: the rule is enforced by a type checker or by code review. Say this in an interview if you implement it in those languages.
Errors are part of the contract. The template method catches a specific family of exceptions: IllegalArgumentException (and ArithmeticException from longValueExact) in Java, ValueError in Python, and a custom ImportError in TypeScript. That family is effectively part of the abstract step's contract: "throw this to reject a row". Catching everything would hide real bugs, which is why the TypeScript version rethrows anything that isn't an ImportError.
Hooks are opt-in. FixedWidthStatementImporter overrides afterImport to write an audit line; the CSV importer doesn't. That's the difference between a hook and an abstract step. If every subclass had to write an empty afterImport, it would be noise.
Money is in integer cents. Both parsers convert to whole cents and reject anything with more than two decimal places. The TypeScript version parses the decimal string by hand rather than multiplying a float by 100, which avoids errors such as 0.29 * 100 giving 28.999999999999996.
Abstract steps vs hooks
The most common design question inside this pattern is "should this step be abstract or a hook?"
| Make it abstract when... | Make it a hook when... |
|---|---|
| There's no correct default | Doing nothing (or a simple default) is correct for most subclasses |
| Forgetting it would be a bug | Forgetting it is harmless |
| It's the reason the subclass exists | It's an optional extension point |
Example: parse(line) | Example: afterImport, headerLines |
Two further kinds of hook are worth knowing.
Decision hooks return a value that changes the flow: headerLines() returns a count, and a shouldSkip(line) hook could return a boolean. They let a subclass steer the algorithm without overriding it.
Before and after hooks surround a step: beforeImport(), afterImport(). Frameworks use these heavily. Every test framework's set-up and tear-down methods are this shape.
Keep the total number small. A base class with ten hooks is a configuration file written as inheritance, and subclass authors have to read the base class line by line to know which hooks interact.
The "call super" smell and how Template Method fixes it
A common alternative to Template Method is to make the whole method overridable and ask subclasses to call super at the right point:
class Base {
void importText(String text) {
// ...shared work...
}
}
class Csv extends Base {
@Override void importText(String text) {
// ...skip header...
super.importText(text); // must remember this, and at the right moment
// ...audit...
}
}
This is fragile. Nothing forces the subclass to call super, nothing checks it calls it at the right moment, and the base class can't change its internal order without breaking subclasses. Template Method inverts the relationship: the base class keeps control and calls down into small named steps, so the subclass never needs to call up. When you see a comment like "subclasses must call super.foo() first", that's the signal to refactor.
The constructor trap
Template methods call overridable methods. If one of them runs from the base class constructor, it runs before the subclass's own constructor has finished, so the subclass's fields are still unset.
public class ConstructorTrap {
static abstract class Report {
final String titleSeenInConstructor;
Report() { titleSeenInConstructor = title(); } // calls an overridable method
abstract String title();
}
static final class SalesReport extends Report {
private final String region;
SalesReport(String region) {
super(); // Report() runs first and calls title()...
this.region = region; // ...before this line has run
}
@Override String title() { return "Sales " + region; }
}
public static void main(String[] args) {
SalesReport report = new SalesReport("EMEA");
assert report.titleSeenInConstructor.equals("Sales null");
assert report.title().equals("Sales EMEA");
System.out.println("constructor trap: all assertions passed");
}
}
The same thing happens in Python when a base __init__ calls a method that reads attributes the subclass sets after super().__init__(), and in TypeScript, where subclass field initialisers run only after super() returns. The rule is simple: never call a template method, or any overridable step, from a constructor. Construct the object first, then call the template method. If you need "initialise on creation", use a static factory that constructs and then calls init().
Template Method with functions instead of inheritance
Template Method is a choice to vary steps by subclassing. The alternative is to keep one concrete class and pass the varying steps in as functions. That is Strategy for a single step, and in languages with first-class functions it is often simpler:
type Transaction = { date: string; description: string; amountCents: number };
type ImporterSteps = {
parse: (line: string) => Transaction;
headerLines?: number;
afterImport?: (accepted: Transaction[]) => void;
};
// The skeleton is still fixed. The variation arrives as data, not as a subclass.
function importText(text: string, steps: ImporterSteps): Transaction[] {
const lines = text.split("\n").filter((l) => l.trim() !== "");
const accepted = lines.slice(steps.headerLines ?? 0).map(steps.parse).filter((t) => t.amountCents !== 0);
steps.afterImport?.(accepted);
return accepted;
}
const pipeSeparated: ImporterSteps = {
headerLines: 1,
parse: (line) => {
const [date = "", description = "", cents = "0"] = line.split("|");
return { date, description, amountCents: Number(cents) };
},
};
const out = importText("date|desc|cents\n2026-11-07|Book|-1999\n2026-11-08|Void|0", pipeSeparated);
if (out.length !== 1 || out[0]?.amountCents !== -1999) throw new Error("functional template failed");
console.log("functional template: all assertions passed");
How to choose:
| Prefer subclassing (Template Method) when... | Prefer passed-in functions when... |
|---|---|
| The steps share state, such as fields set up in one step and read in another | The steps are independent and stateless |
| There are several related steps that vary together | Only one or two steps vary |
| The variants are long-lived, named concepts ("the CSV importer") | Variants are created ad hoc or configured at run time |
| You need a protected API that only subclasses may call | You want to mix and match steps freely |
The second column wins more often in modern code, for one reason: inheritance gives you one axis of variation. Suppose imports vary by format (CSV, fixed-width, OFX) and by destination (database, preview, dry run). With subclassing you need a class for every combination, nine classes for three of each. With composition you need three parsers and three destinations, combined freely. When you see the subclass count multiplying, switch from Template Method to Strategy. OOP fundamentals covers the general composition-over-inheritance argument.
Real-world uses
java.io.InputStream. Subclasses must implement the abstract single-byteread(). The base class implementsread(byte[], int, int),skipand others in terms of it, and fast subclasses override those for speed. A textbook template method with optional overrides.java.util.AbstractList. Implementget(int)andsize(), and you inherit a working iterator,contains,indexOf,equals,hashCodeand more, all written as template methods over your two primitives.AbstractMapandAbstractSetfollow the same idea.HttpServlet.service. The servlet API'sservicemethod inspects the HTTP method and dispatches todoGet,doPostand the rest, which subclasses override. The defaults respond with an error saying the method isn't supported.- Test frameworks. JUnit 3's
TestCaseransetUp(), then the test, thentearDown(); Python'sunittest.TestCasehas the samesetUp/tearDownhooks around each test method. Newer frameworks moved to annotations and fixtures, but the shape is the same. threading.Threadin Python.start()handles creating the thread and then callsrun(), which subclasses may override. Passing atargetfunction instead is the composition alternative, and it is what most code does today.- Spring's
JdbcTemplate. Despite the name, it is the functional form: the template opens the connection, prepares the statement, translates exceptions and releases resources, and you pass a callback such as aRowMapperfor the part that varies. - UI component lifecycles. React class components define
renderand optional lifecycle hooks such ascomponentDidMount, and the framework calls them at the right times. That is the Hollywood principle at framework scale.
When NOT to use it
- When there is only one implementation. An abstract class with one subclass is speculative structure. Write the concrete class, and extract the template when the second variant appears and you can see what actually differs.
- When variation runs along more than one axis. Subclass counts multiply. Use composition: pass in parsers, writers and policies separately.
- When steps are swapped at run time. A subclass is chosen at construction and fixed for the object's life. If a user can switch the step from a settings page, a strategy field is the right tool.
- When the "skeleton" is two lines. If the template method is just
a(); b();, the abstraction costs more than the duplication it removes. - When subclasses need to change the order. If variants keep asking for "the same steps, but validate before parsing", the skeleton isn't really shared. Model the steps as a list of handlers instead, which is closer to Chain of Responsibility or a pipeline.
The costs to remember: tight coupling between base class and subclasses (a change to the base's step order can break every subclass), a protected API that is hard to evolve, and code that is harder to follow because the flow jumps between the base and the subclass. This is the fragile base class problem in its most common form.
Related patterns
Strategy. The closest relative and the usual alternative. Template Method varies part of an algorithm through inheritance and is fixed at compile time. Strategy replaces a whole algorithm, or a single step, through composition and can be swapped at run time. A useful rule: if the variation is one step and has no shared state, pass a function.
Factory Method. Very often a step inside a template method. createParser() called from a template importText() is a factory method. The two patterns share the same mechanism, an overridable method called by the base class; Factory Method is the special case where the step's job is to create an object.
Hooks and Observer. A hook is a single, compile-time extension point owned by one subclass. Observer is a list of run-time subscribers. If several independent parties want to react "after import", replace the afterImport hook with an event that many listeners can subscribe to.
Chain of Responsibility. When the steps themselves need to be reordered, added or removed per variant, a fixed skeleton is the wrong shape. A chain or pipeline of handlers makes the sequence configurable.
Visitor. Visitors often have a template-like base class with default "visit children" behaviour, which concrete visitors override for the nodes they care about.
The smell that suggests it
- Two or more classes with nearly identical methods that differ in a few lines in the middle.
- A bug fixed in one copy of an algorithm but not the others, or a rule that applies in one variant only by accident.
- Comments like "subclasses must call super first" or "remember to call
validate()before saving". - A long method with a
switchon a type in the middle, where every case runs the same before and after code. - New variants are created by copying an existing class and editing it.
Interview questions
-
"What's the difference between Template Method and Strategy?" Template Method fixes the skeleton in a base class and varies steps through inheritance, so the choice is fixed at compile time and per class. Strategy delegates a whole algorithm or step to a separate object passed in through composition, so it can be swapped at run time and combined freely. I default to Strategy unless the steps share state or there are several related steps that vary together.
-
"Why make the template method final?" So subclasses can't reorder, skip or wrap the steps. The whole point is that the algorithm's structure, including validation and error handling, is guaranteed. Without
final, a subclass can override the template and the guarantee is gone. -
"What's a hook, and how is it different from an abstract method?" An abstract method has no default and every subclass must implement it. A hook has a safe default, often empty, and subclasses override it only when they need to. Use abstract for the reason a subclass exists, and hooks for optional extension points.
-
"What is the Hollywood principle?" "Don't call us, we'll call you." The base class or framework decides when your code runs and calls it; your code doesn't call the framework's internals. Template Method is the class-level version of it, and frameworks are the large-scale version.
-
"Can you call a template method from a constructor?" You shouldn't. Overridable steps would run before the subclass's constructor has set its fields, so they see default values (
null,0). Construct first, then call the template, or use a static factory that does both. -
"Your importer now needs to vary by format and by destination. What changes?" Template Method would need a subclass per combination. I'd switch to composition: inject a parser for the format and a sink for the destination into one concrete importer. Each axis gets its own small interface, and new combinations need no new classes.
-
"How would you test a template method?" Test the skeleton once using a minimal test subclass whose steps record calls or return canned values. That checks ordering, header skipping and error collection in one place. Then test each concrete subclass's steps directly, mostly the
parselogic, with a few end-to-end cases. -
"Is Template Method a violation of composition over inheritance?" It's the pattern that rule warns about most often, but it's legitimate when the subclass really is a specialisation and the steps share state. The warning applies when inheritance is used only to reuse code, or when variation spans several axes.
Further reading
- Behavioral patterns overview: the short version, with a data-exporter example.
- Strategy pattern: the composition-based alternative.
- Factory Method pattern: a template method whose step creates an object.
- Open/closed principle: adding a variant without editing the skeleton is open/closed in action.
- Common LLD mistakes: when inheritance is the wrong tool.
- Pattern selection guide: Template Method next to Strategy and the other look-alikes.