Pattern 01/22 · Behavioral
Template Method
Pin down the order of an algorithm's steps in exactly one place and leave open only the steps that can vary. The GoF version opens them through inheritance; the modern JS version opens them through hooks/callbacks.
01 — It starts with code that is breaking
Problem
You write a job that imports users from CSV: read the file, split it into lines, normalize each line, insert into the DB, print an "x/y rows" report. A week later you need a product import. You copy that function, change exactly the normalization part, rename it. Then a third job: orders from a partner, and this time the source is a JSON body, not a file.
Now three import functions contain the same process and two different lines. Copy-pasting the third time doesn't slow you down by a second; the problem shows up later. Dev A notices the process has no retry and fixes it in importUsers(). Dev B hits the same issue in importOrders() three weeks later, doesn't know A already fixed it, and fixes it again from scratch. Version 3 of the process is somewhere in git.
The same disease shows up in a second form elsewhere: a class with six methods where the caller has to remember the right call order: connect(), auth(), subscribe(), then close() in finally. Someone forgets close(). Someone calls subscribe() before auth(), and it seems to work until the broker changes its policy. The "always close the connection" invariant lives in the author's head, not in the code.
Both smells have the same root cause: the process part (step order, resources, error handling) is mixed in with the business part (what a row of data turns into), so the process gets copied and fixed wrong in each copy. You don't need fewer import functions. You need one place that owns the process.
This is where an old pattern has a very clear answer, even in code with no classes at all: the framework owns the flow, you fill in the blanks.
02 — The idea, before touching code
Solution
Separate the skeleton from the steps. The skeleton is a function (usually called run, execute, handle) that lists the step order exactly once: read → split → normalize → write → report. It holds no business logic; it just calls the "blanks". The blanks are declared as protected abstract methods (you must implement them) and empty methods (hooks: implement them if you want, skip them if you don't).
The GoF version opens the steps through inheritance: abstract class ImportPipeline holds the skeleton, and each ConcretePipeline overrides exactly its own step. In modern JS/TS the same structure is expressed with composition: a function that takes an options object, where each variable step is a property with a default. The power comes from inversion of control: your code doesn't call the framework, the framework calls your code, so step order, transactions, cleanup and logging can't be forgotten, not even by a new hire.
Why is this pattern "invisible" in JS? Because nobody calls it by its GoF name anymore. It's onMounted, it's beforeEach, it's route middleware, it's app.use(plugin), it's a stream's _transform(). You've written Template Method a hundred times. What the pattern gives you isn't new syntax; it's the vocabulary to recognize when the flow should live in the framework instead of in the caller's memory.
03 — Doing it for real, one code fragment per step
Step by step
Sort the steps: invariant vs. variable
Before touching the code, write the process down as a list of steps and ask of each one: "does this step change with the kind of data?" The import process: read the source, split it into lines, normalize one line, write each row, report the totals.
Of the five steps, exactly one really changes per source type. The rest is process that must run in full every time, and that is precisely what shouldn't be left in the caller's hands.
IMPORT PROCESS INVARIANT?
1. read the source (file / HTTP body / stream) YES -> one reader per source type
2. split the source into lines YES -> CSV differs from JSON
3. normalize ONE line -> row | null NO -> this is the variable step
4. write each row (insert / upsert) YES -> identical everywhere
5. report totals (x/y rows) YES -> identical everywhere
=> Skeleton = 1 + 2 + 4 + 5 (+ order + errors + cleanup).
=> Hook = step 3, and optionally steps 1/2/5.Write the copy-paste version, then see where it diverges
Nobody sets out to write three copies of the same process. It happens naturally: the second job needs exactly two lines different from the first, and copying is the shortest path.
async function importUsers(body: string): Promise<void> {
const rows = body.split('\n').filter(l => l.trim() !== '')
let kept = 0
for (const raw of rows) {
const parts = raw.split(',')
if (parts.length < 2) continue
await db.insert(users).values({ name: parts[0], email: parts[1] })
kept++
}
console.log('users: ' + kept + '/' + rows.length)
}
async function importProducts(body: string): Promise<void> {
const rows = body.split('\n').filter(l => l.trim() !== '') // <— identical
let kept = 0 // <— identical
for (const raw of rows) { // <— identical
const parts = raw.split('|') // <- different: the separator
if (parts.length < 3) continue
await db.insert(products).values({ sku: parts[0], name: parts[1], price: parts[2] })
kept++
}
console.log('products: ' + kept + '/' + rows.length)
}Build the skeleton: one function that runs the whole process
The skeleton is a single function that lists the process once. It calls the steps through this and holds no business logic itself. From now on, adding a new data type means writing a subclass, not rewriting the loop.
Notice what you got without meaning to: the invariant "a rejected row is never written" now exists in exactly one place. In the copy-paste version it was a continue that everyone had to remember to write again.
export abstract class ImportPipeline {
/** Skeleton: the step order lives here and nowhere else. */
run(input: string): number {
const rows = input.split('\n').filter(l => l.trim() !== '')
console.log(' read: ' + rows.length + ' valid lines')
let kept = 0
for (const raw of rows) {
const row = this.transformRow(raw)
if (row === null) continue // <-- the invariant lives HERE, not in the subclass
this.write(row)
kept++
}
this.summary(rows.length, kept)
return kept
}
protected abstract transformRow(raw: string): string | null
protected write(row: string): void { console.log(' write: ' + row) }
protected summary(total: number, kept: number): void {}
}Close the skeleton, open exactly the hooks
The skeleton only means something if nobody overrides it. TypeScript has no final, so the standard move is: declare the skeleton private, and have clients go through a paper-thin entry point execute() that only calls the skeleton. A subclass that wants to change the flow simply... can't.
Then open exactly three slots: transformRow is required (abstract, the compiler forces you to write it), write and summary are hooks with defaults. A minimal subclass needs just one method.
export abstract class ImportPipeline {
/** The only entry point for clients. Holds 0 logic, so overriding it gets you nothing. */
execute(input: string): number {
return this.run(input)
}
/** The template method. Private is how you say: "this order isn't yours". */
private run(input: string): number {
const rows = input.split('\n').filter(l => l.trim() !== '')
console.log(' read: ' + rows.length + ' valid lines')
let kept = 0
for (const raw of rows) {
const row = this.transformRow(raw)
if (row === null) {
this.onRejected(raw)
continue
}
this.write(row)
kept++
}
this.summary(rows.length, kept)
return kept
}
protected abstract transformRow(raw: string): string | null
protected write(row: string): void { console.log(' write: ' + row) }
protected onRejected(raw: string): void { console.log(' reject: ' + raw) }
protected summary(total: number, kept: number): void {
console.log(' done: ' + kept + '/' + total)
}
}Required steps (abstract) vs. empty hooks: pick the right one
GoF calls a required step a primitive operation and an optional step a hook. In TypeScript terms: required = abstract (the compiler blocks you; skip it and it won't build), optional = empty body (a subclass can stay silent).
Picking the wrong side costs you either way. Make too much required and the codebase fills up with {} methods commented "does nothing"; make an important step optional and some subclass will forget it and silently do the wrong thing. Ask: if a subclass doesn't implement this step, is that a bug?
/** REQUIRED: if the subclass doesn't write it, it doesn't build. Use it for the job's core step. */
protected abstract transformRow(raw: string): string | null
/** HOOK: plug metrics/cache/audit in here if needed. Otherwise ignore it. */
protected onWrite(row: string): void {}
/** HOOK WITH MEANING: the default is to throw. Subclasses only change HOW it's reported, not the flow. */
protected onError(raw: string, e: unknown): void {
throw e
}abstract = the compiler demands it. {} = the subclass is allowed to ignore it. Keep the number of hooks smaller than what a person can remember.The modern JS version: hooks are functions, no inheritance needed
TypeScript only lets you extend one class. And modern JS code rarely uses classes as the unit of reuse. Write the same skeleton with composition: a factory takes options, each variable step is a property with a default, and it returns a function that runs the process.
This is still exactly Template Method: a fixed skeleton, blanks filled in by someone else, flow decided by the skeleton. Only the mechanism for opening it differs. And that's why the pattern is nearly invisible in JS: it shows up as options, hooks, plugins, createX, not under its GoF name.
export interface PipelineOptions<T> {
split?: (input: string) => string[]
transform: (raw: string) => T | null
write?: (row: T) => void
summary?: (total: number, kept: number) => void
}
const defaultSplit = (input: string) => input.split('\n').filter(l => l.trim() !== '')
/** Fixed skeleton. Variable step = property with a default. */
export function createPipeline<T>(o: PipelineOptions<T>) {
const split = o.split ?? defaultSplit
const write = o.write ?? ((row: T) => console.log(String(row)))
return (input: string): number => {
const rows = split(input)
let kept = 0
for (const raw of rows) {
const row = o.transform(raw)
if (row === null) continue
write(row)
kept++
}
o.summary?.(rows.length, kept)
return kept
}
}
const importUser = createPipeline({
transform: raw => (raw.includes(',') ? raw.split(',')[0] : null),
})Many parties need the same slot: middleware, plugins, interceptors
Inheritance has a limit you can't fix: a class has only one parent. When five teams all want to inject logic into the "before write" step, a single hook isn't enough. The middleware model is Template Method multiplied: the frame still runs one pass in a fixed order, but each slot is open to N parties.
This is the shape you meet most often in the JS world: Koa/Express, Nuxt route middleware, Vue plugins, axios interceptors, Apollo/GraphQL middleware. You don't extend anything, and that's a good thing.
type Ctx = { url: string, ms?: number }
type Next = () => Promise<void>
type Middleware = (ctx: Ctx, next: Next) => Promise<void>
/** Fixed skeleton: middleware runs in order, then the handler. */
export function compose(middlewares: Middleware[], handler: Next) {
return async (ctx: Ctx): Promise<void> => {
const dispatch = (i: number): Promise<void> =>
i === middlewares.length ? handler() : middlewares[i](ctx, () => dispatch(i + 1))
return dispatch(0)
}
}
export const logTiming: Middleware = async (ctx, next) => {
const t0 = performance.now()
await next() // <-- the frame decides when the next step runs
ctx.ms = performance.now() - t0
}Acceptance test: add a new import type without copying the loop
The final test of this refactor: add a new data type by writing only the variable step. If you have to copy the loop, the skeleton isn't done.
import { ImportPipeline } from './import-pipeline-v2'
/** XML source: only declares steps 3 and 5. No copied loop. */
class XmlImport extends ImportPipeline {
protected transformRow(raw: string): string | null {
if (!raw.startsWith('<row name="') || !raw.endsWith('"/>')) return null
return raw.slice(11, -3)
}
protected summary(total: number, kept: number): void {
console.log(' done: ' + kept + '/' + total + ' XML rows')
}
}
new XmlImport().execute('<row name="an"/>\n<blank/>\n<row name="linh"/>')read: 3 valid lines write: an reject: <blank/> write: linh done: 2/3 XML rows
04 — Who talks to whom
Structure
- AbstractClassHolds the **skeleton** (`run`/`execute`) that lists the step order exactly once, plus safe defaults for the hooks.
- TemplateMethodThe skeleton itself. Calls the steps in order, owns transactions/cleanup/logging. Never overridden.
- PrimitiveOperationA required step: `abstract`. If the subclass doesn't implement it, it doesn't build.
- HookAn optional step with an empty or sensible default. Where metrics, audit, caching and reporting plug in.
- ConcreteClass / CallerOverrides exactly its own steps (or passes hook functions). Doesn't decide the flow.
Client ─── execute(input) ───► (never calls the steps itself)
│
┌───────────────────▼──────────────────┐
│ AbstractClass │
│ private run(input) ← SKELETON │ fixed
│ 1 split() [default] │ order,
│ 2 transformRow() [abstract] │ nobody
│ 3 write() [default] │ overrides
│ 4 summary() [empty hook] │
└───────────────────┬──────────────────┘
skeleton calls back down (Inversion of Control)
┌───────────────┼────────────────┐
▼ ▼ ▼
┌────────────┐ ┌────────────┐ ┌──────────────┐
│ UserImport │ │ CsvImport │ │ XmlImport │
│ transform │ │ split+ │ │ transform │
│ + summary │ │ transform │ │ + summary │
└────────────┘ └────────────┘ └──────────────┘
override ONLY their own steps, never copy the process05 — Edit freely, run it right here
Try it: two import pipelines sharing exactly one skeleton
abstract class ImportPipeline {
/** Template method: fixed step order. Subclasses don't touch this. */
run(input: string): number {
const rows = input.split('\n').filter(l => l.trim() !== '')
console.log(' read: ' + rows.length + ' valid lines')
let kept = 0
for (const raw of rows) {
const row = this.transformRow(raw)
if (row === null) { console.log(' reject: ' + raw); continue }
console.log(' write: ' + row)
kept++
}
this.summary(rows.length, kept)
return kept
}
/** Variable step: every subclass fills it in. */
protected transformRow(raw: string): string | null { return raw.trim() }
/** Empty hook: override it if you want. */
protected summary(total: number, kept: number): void {}
}
class UserImport extends ImportPipeline {
protected transformRow(raw: string): string | null {
const p = raw.split(',')
return p.length < 2 ? null : p[0].toUpperCase() + ' <' + p[1] + '>'
}
protected summary(total: number, kept: number): void {
console.log(' done: ' + kept + '/' + total + ' rows')
}
}
class RawImport extends ImportPipeline {} // overrides nothing, uses all the defaults
const csv = 'an,an@x.io\n\nno-email\nlinh,linh@x.io'
console.log('UserImport:')
new UserImport().run(csv)
console.log('RawImport:')
new RawImport().run(csv)UserImport: read: 3 valid lines write: AN <an@x.io> reject: no-email write: LINH <linh@x.io> done: 2/3 rows RawImport: read: 3 valid lines write: an,an@x.io write: no-email write: linh,linh@x.io
The same code runs on Bun: bun run demo.ts. Its output is checked automatically when the site is built.
06 — Honest about the cost
When to use it, when not to
Use it when
- A multi-step process where order matters, and only a few steps change with the data type or source type.
- There are mandatory invariants (always release resources, always commit/rollback, always put a trace id in the logs). Put them in the skeleton and nobody can forget them; leave them in the caller's head and sooner or later someone will.
- The caller shouldn't need to know the call order. You want "the framework calls you back" rather than "you call the framework".
- Several teams/plugins need to inject behavior at the same point: open a list of hooks, not a single
protectedmethod. - You're copying a function to change two lines: the skeleton already exists, it just hasn't been extracted yet.
- You're writing a framework/SDK/composable for others: they should only fill in business logic, not manage your lifecycle.
Don't use it when
- Inheritance is a shackle: a class can extend only one skeleton. Needing two skeletons at once means the design is wrong: switch to composition right away, don't patch it with three layers of mixins.
- Hook bloat is its own disease: 12 hooks means 12 places where behavior can change from afar, and nobody can predict what runs when anymore. Log step numbers and clearly mark which hooks are required.
- Debugging gets harder because the stack trace runs through the base class and someone reading the subclass can't see the flow. Put a one-line comment at the top of each subclass: "the flow lives in the base class's run()".
- Over-engineering: if two variants differ even in the order of steps, a skeleton can't express that, and forcing it into one is a lie. That's when a pipeline array (a list of steps built at runtime) or Strategy is the right tool.
- Don't let hooks change the step order unless you really need that much power.
onBefore/afterhooks are safer than hooks that receivenext, because a hook that receivesnexthas the power to not call it, and that's a very hard bug to find. abstracthardens your API: adding a newabstractto the base class breaks every existing subclass. Adding a hook with a default is safe.
07 — You have met it already, just not by name
In real code
Vue lifecycle hooks
onMounted, onBeforeUnmount, onUpdated... Vue keeps the mount/update/unmount algorithm fixed and calls your hooks when it decides to. You don't call onMounted(); it gets called. That's Template Method's inversion of control exactly. And Vue does it with functions, not classes.
Node.js stream.Transform
Extend Transform, implement _transform(chunk, enc, cb) and _flush(cb). Buffering, backpressure, chunk order: Node owns those; you fill in one step. Textbook GoF Template Method, right in the core API.
Jest/Vitest beforeEach / afterEach
The test runner has a skeleton: setup → run test → teardown → report. Your hooks are the variable steps. If every test handled its own setup, you'd be right back at the copy-paste version from the problem section.
Nuxt route middleware & definePageMeta
The router runs a fixed pipeline (resolve route → run middleware → validate → render) and calls your middleware one at a time, in order. You never call the next middleware by hand.
Custom Elements
The browser calls connectedCallback, disconnectedCallback, attributeChangedCallback on the class you register. The browser is the framework and the flow is its own; you just fill in the steps.
08 — Try it yourself
Exercise
Extract the boilerplate of your background jobs (log start, try/catch, log end, report errors) into a skeleton, so that adding a new job means writing **only** the body. How do you make it impossible for a job to forget the error-reporting step?
Hints, open them one at a time:
- The skeleton should be
private(or at least not a place meant for overriding); clients go throughexecute(). - Split out three hooks:
work()is required (abstract),onSuccess()andonError()have defaults. - Make the default
onErrorrethrow: if a subclass wants to swallow errors it has to say so explicitly. That's a deliberate decision, not something forgotten.
An abstract class holds execute(), which calls work() inside try/catch, logs before/after, and calls onSuccess/onError. work() is abstract, so the compiler forces every job to implement it; the default onError rethrows, so no job can "forget" error reporting without consciously writing code to do so.
abstract class Job {
constructor(readonly name: string) {}
/** Skeleton: no job is allowed to skip reporting. */
execute(): void {
console.log('[' + this.name + '] start')
try {
this.work()
this.onSuccess()
}
catch (e) {
this.onError(e as Error)
}
console.log('[' + this.name + '] done')
}
protected abstract work(): void
protected onSuccess(): void { console.log(' ok') }
protected onError(e: Error): void { console.log(' ERROR: ' + e.message) }
}
class SyncPrices extends Job {
protected work(): void { console.log(' synced 1280 items') }
}
class SendReport extends Job {
protected work(): void { throw new Error('SMTP not responding') }
}
new SyncPrices('sync-prices').execute()
new SendReport('send-report').execute()09 — Read them in pairs to see the essence
Related patterns
- StrategySame goal (let one step of an algorithm be swapped), but Template Method does it with inheritance (chosen at write time) and Strategy with composition (chosen at runtime). Strategy is more flexible; Template Method is safer about step order.
- StateA natural pair: the skeleton decides **when** a step runs, State decides **which behavior** is currently valid. A state machine plus Template Method is the backbone of a workflow engine.
- CommandCommand turns "work to do" into an object you can feed into a skeleton (queue, retry, undo). The skeleton handles the lifecycle, the Command handles the content.
- FacadeFacade hides a subsystem behind a simple entry point and **opens** nothing; Template Method also locks down an entry point but **opens exactly a few steps** for whoever comes next.