Template Method
Intent
Fix the skeleton of an algorithm in a base unit and let subclasses vary only specific steps.
Motivation
Monthly reports export through identical steps — fetch data, format it, save the file — but CSV and PDF format differently. Copying the whole pipeline per format duplicates fetch and save and lets them drift. A base exporter that owns the step order and leaves only the format step open keeps one pipeline with two interchangeable endings.
Structure
flowchart LR Base[Report Base] --> Fetch[fetch data] Fetch --> Format[format - varies] Format --> Save[save file] Format --> CSV[CSV Export] Format --> PDF[PDF Export]
- Abstract base (Report) — owns the template: the fixed step order and shared steps.
- Primitive step (format) — the one step subclasses override.
- Concrete exports (CSV, PDF) — fill in only the varying step.
Consequences
- Benefit: shared steps are written once; the step order is enforced so variants cannot skip stages.
- Cost: the base dictates structure — an odd variant that needs a different order fights the template (consider Strategy instead).
Basic Recap
Template Method defines the skeleton of an algorithm in a base operation and leaves selected steps to subclasses or hook implementations. The invariant sequence remains in one place, while variable details are supplied through primitive operations. Callers invoke the template rather than assembling the steps themselves. The base class therefore controls extension points and must make preconditions, resource ownership, and hook ordering clear.
Complex Scenario
A data synchronization framework defines runSync as open checkpoint, extract,
transform, load, and finalize. Vendor integrations implement extraction and
optional transformation, while the base template consistently handles telemetry,
checkpoint progression, and resource cleanup. A failed load can resume from the
last durable checkpoint without rerunning an entire day of extraction. New
connectors override a small set of documented steps instead of copying the
synchronization loop.
Edge cases
- Partial failure: A checkpoint written before data is durably loaded can skip records after a crash, so checkpoint advancement belongs after confirmed load and inside a well-defined consistency boundary.
- Retries: A retry may repeat an ambiguous load, making idempotent merge keys necessary even if the template itself runs the same sequence.
- Ordering: Optional hooks such as schema validation must run at a fixed, documented point; letting subclasses reorder finalization can bypass cleanup.
Prefer narrow hooks over allowing every step to be replaced. A template that no longer guarantees its invariant sequence offers little value.
Sketch (illustrative pseudocode, not runnable):
SyncTemplate.runSync():
resources = acquireResources()
try:
checkpoint = checkpoints.load(syncKey)
batch = extract(checkpoint) # required primitive
prepared = transform(batch) # optional hook
receipt = loadIdempotently(prepared, checkpoint.token)
checkpoints.advanceAfter(receipt.durable)
finalizeSuccess(receipt)
finally:
releaseResources(resources)
Connector.transform(batch):
return batch # default, deliberately optional
When to Use / When Not to Use
Use when:
- Several variants share the same step order and differ in one or two steps.
- You want the framework to enforce the pipeline while users plug in details.
Avoid when:
- Variants need different step orders or wholly different flows — prefer Strategy or composition.
Examples
examples/elixir/template-method/examples/dart/template-method/examples/go/template-method/examples/rust/template-method/
Expected outcome: CSV and PDF exports each print their shared steps with their own format stage.
Anti-pattern / Failure Mode
-
Misuse: A skeleton with every step overridable — subclasses can break the invariant.
-
Review signal: Deep template hierarchies where the fixed part keeps changing.
-
Misuse symptom: Subclasses override nearly the entire algorithm, call hooks in a different order, or must know undocumented base-class fields to work. Deep inheritance chains make a small change in the base silently alter every integration.
-
Review signal: Watch for public calls that bypass the template and invoke primitive steps directly, empty hooks with surprising required behavior, and base methods whose contracts exist only in implementation comments. Connector tests should verify crash points around loading and checkpointing, not just a successful happy-path sequence.
Related
- Strategy — subclass the step vs inject it.
- Report Generator — template isolates report jobs across workers.
- Composition over Inheritance — prefer injection when the skeleton churns.
Exercise
Add an HTML exporter that varies only the format step. Then try adding one that also needs an extra “chart” step — note where the template resists and what you would change.
Self-check
- Who controls the step order?
Answer
The base template method — subclasses fill steps but never reorder them. - What may a subclass change?
Answer
Only the designated primitive steps (here: format); shared steps stay inherited untouched. - Template Method vs Strategy: what differs?
Answer
Template fixes the skeleton and varies steps by inheritance; Strategy swaps the whole step by delegation at runtime.