A company pays three kinds of people. Staff get a fixed monthly salary. Contractors bill by the hour. Sales staff get a base salary plus commission. Their pay is calculated differently, but every pay slip goes through the same steps in the same order. The payroll works out the gross pay, then takes off the provident fund, professional tax and any tax deducted at source. The slip shows what is left.
Many programs have work shaped like this. A data import reads a file, checks each row, converts it and saves it, and only the reading differs between CSV and Excel. A board game plays a turn the same way for every game, and only the moves differ. The order of the steps is fixed, and a few of the steps change.
The Template Method pattern writes the order once, in a base class, and leaves the steps that change to subclasses. In this article we build the pay slips twice. The first version has three classes that each copy the whole flow. The second uses the Template Method pattern. Then we look at what the pattern costs, how it differs from Strategy, and how it shows up in interviews.
All the code is Java. Every snippet without a Sketch label is cut from a project that compiles: the first-version snippets from the copied version, the rest from the finished design. The Open file button on a finished-design snippet shows the whole file in a code browser.
The payroll we are building
The rules here are simplified to keep the example small. They are not real tax law. In the code every amount is a long of cents, so $6,000 is written 6_000_00, and the slip rounds each line to whole dollars. A salary or hourly rate below $1 is refused.
- Gross pay depends on the kind of worker. Staff get their monthly salary. Contractors get their hourly rate for the minutes they worked. Sales staff get a base salary plus a commission on sales above their monthly target.
- Provident fund is 12% of the worker's wages, capped at $180. For most workers the wages are the gross pay. Contractors are not on the provident fund. Sales staff pay it on their base salary only, never on commission.
- Professional tax is $20 when gross pay is above $1,500, and nothing otherwise. The rule is the same for everyone.
- Tax deducted at source is 10% of gross pay for contractors, and nothing for anyone else.
- Every amount is rounded to whole dollars, and half a dollar rounds up. The same rule applies to every line on every slip.
- The slip lists the deductions in one order: provident fund, then professional tax, then tax deducted at source. The net pay is the gross minus the deductions.
This table is the thing to draw first. It separates the steps that vary from the steps that must never vary. The steps that vary become the subclasses' job. The order, and every step that is the same for everyone, stays in one place.
The first version: three copies of the same steps
The obvious way to write this is one class per kind of worker, each with its own payFor method that does every step. Here is the salaried one:
public PaySlip payFor(WorkMonth month) { long gross = toWholeDollars(monthlySalary); List<Deduction> deductions = new ArrayList<>(); long providentFund = toWholeDollars(Math.min(gross * 12 / 100, 180_00)); if (providentFund > 0) { deductions.add(new Deduction("Provident fund", providentFund)); } if (gross > 1_500_00) { deductions.add(new Deduction("Professional tax", 20_00)); } long net = gross; for (Deduction deduction : deductions) { net -= deduction.amount(); } return new PaySlip(id, name, "Salaried", month.month(), gross, deductions, net, List.of()); } private long toWholeDollars(long cents) { return (cents + 50) / 100 * 100; }ContractorPay and SalesPay look the same, with their own gross pay and their own deductions. Every class has its own copy of the professional tax rule, the rounding rule and the order. Here is the contractor's:
public PaySlip payFor(WorkMonth month) { long gross = toWholeDollars(month.minutesWorked() * hourlyRate / 60); List<Deduction> deductions = new ArrayList<>(); if (gross > 1_500_00) { deductions.add(new Deduction("Professional tax", 20_00)); } long taxDeducted = toWholeDollars(gross * 10 / 100); if (taxDeducted > 0) { deductions.add(new Deduction("Tax deducted at source", taxDeducted)); } long net = gross; for (Deduction deduction : deductions) { net -= deduction.amount(); } int hours = month.minutesWorked() / 60; int minutes = month.minutesWorked() % 60; String note = hours + " h " + minutes + " min at " + PaySlip.dollars(hourlyRate) + " an hour"; return new PaySlip(id, name, "Contractor", month.month(), gross, deductions, net, List.of(note)); } private long toWholeDollars(long cents) { return cents / 100 * 100; }And here is the part of the sales version that adds the deductions:
long aboveTarget = Math.max(0, month.salesCents() - monthlyTarget); long gross = toWholeDollars(baseSalary + aboveTarget * commissionBasisPoints / 10_000); List<Deduction> deductions = new ArrayList<>(); if (gross >= 1_500_00) { deductions.add(new Deduction("Professional tax", 20_00)); } long providentFund = toWholeDollars(Math.min(baseSalary * 12 / 100, 180_00)); if (providentFund > 0) { deductions.add(new Deduction("Provident fund", providentFund)); }Each class works on its own. The trouble shows when the three are put side by side. This is the first version's output for one month:
W-1 Asha Rao (Salaried), March 2026 Gross pay $6,000 Provident fund -$180 Professional tax -$20 Net pay $5,800 W-2 Ravi Kumar (Contractor), March 2026 Gross pay $8,281 Professional tax -$20 Tax deducted at source -$828 Net pay $7,433 162 h 23 min at $51 an hour W-3 Meera Iyer (Sales), March 2026 Gross pay $1,937 Professional tax -$20 Provident fund -$144 Net pay $1,773 Commission: 5% of $14,735 above the $20,000 target
The copies have already drifted apart, in three ways:
- Different rounding.
ContractorPayrounds down (line 38), while the other two round half a dollar up. Ravi's gross is $8,281 here, $1 short of what requirement 5 gives him. - Different order.
SalesPayadds professional tax before the provident fund, so Meera's slip lists them the other way round from everyone else's. - A different limit.
SalesPaycharges professional tax when the gross is $1,500 or more (line 24). The others charge it only above $1,500. Today's numbers do not show this, but a sales worker earning exactly $1,500 pays $20 that a salaried worker would not.
Nobody chose any of these differences. They happened because the same rule lived in three places and was changed in only one or two of them. Every change to a shared rule has to be made three times, and nothing in the compiler notices when one copy is missed.
The idea
The Template Method pattern works like this:
- A base class,
Worker, has one method that runs every step in the fixed order. That method isfinal, so no subclass can change the order. - Steps that are the same for everyone are written once in the base class, and are
private, so no subclass can change them. - Steps that every subclass must supply are
abstractmethods. Gross pay is one: there is no sensible default. - Steps that have a sensible default are ordinary methods with a body, which a subclass may override. These are called hooks. The wage the provident fund is worked out on is one: for most workers it is the gross.
- Each kind of worker is a subclass that fills in its abstract steps and overrides only the hooks it needs.
The fixed method is the template method: it is the template that every slip follows. Other pages on this site use the word hook for any step a subclass fills in. Here we keep it for the optional steps, the ones with a default, because the difference matters when you design the base class.
Building it, step by step
Step 1: the template method
payFor is the template method. It runs every step in order, and every slip is made by this one method:
// The template method: the steps and their order are written here once, and final keeps them here. public final PaySlip payFor(WorkMonth month) { Objects.requireNonNull(month, "month"); long gross = toWholeDollars(grossPay(month)); List<Deduction> deductions = new ArrayList<>(); addDeduction(deductions, "Provident fund", providentFund(providentFundWages(gross)), gross); addDeduction(deductions, "Professional tax", professionalTax(gross), gross); addDeduction(deductions, "Tax deducted at source", taxDeducted(gross), gross); long totalDeducted = 0; for (Deduction deduction : deductions) { totalDeducted = Math.addExact(totalDeducted, deduction.amount()); } if (totalDeducted > gross) { throw new IllegalStateException("Deductions of " + totalDeducted + " cents exceed the gross of " + gross + " for " + id); } return new PaySlip(id, name, payType(), month.month(), gross, deductions, gross - totalDeducted, slipNotes(month)); }Line 32 asks the subclass for the gross pay and rounds it. Lines 35 to 37 add the three deductions in the order requirement 6 gives. Lines 39 to 45 add them up and check that they do not exceed the gross. The slip is built at the end. No subclass appears anywhere in this method: it calls grossPay and the hooks, and Java runs whichever version the actual worker has.
Should the template method be final?
Leave it overridable
A subclass that needs something unusual can override payFor and do its own thing. But then that subclass can also reorder the deductions, skip the rounding or forget professional tax, which are exactly the bugs the first version had. The base class could no longer promise anything about a slip.
Make it finalOur pick
The order and the shared rules are fixed in one place, and the compiler refuses any subclass that tries to override payFor. If a new kind of worker needs a different flow, that is a sign it is not a Worker in this sense, and it should be its own class.
Step 2: the steps every worker must write
Gross pay and the name of the pay type have no sensible default, so they are abstract:
// Steps every worker type must write. protected abstract long grossPay(WorkMonth month); protected abstract String payType();A subclass that forgets one does not compile. Here is the whole salaried worker. It writes the two abstract steps and accepts every hook's default:
public final class SalariedEmployee extends Worker { private final long monthlySalary; public SalariedEmployee(String id, String name, long monthlySalary) { super(id, name); if (monthlySalary < 1_00) { throw new IllegalArgumentException("A monthly salary must be at least $1, got " + monthlySalary + " cents"); } this.monthlySalary = monthlySalary; } @Override protected long grossPay(WorkMonth month) { return monthlySalary; } @Override protected String payType() { return "Salaried"; }}The constructor checks its own input. A salary below $1 is refused with an IllegalArgumentException, because that is a mistake in the data, and it is better found when the worker is set up than on payday.
Is the provident fund wage an abstract step or a hook?
An abstract step
Every subclass writes its own providentFundWages. Nothing is hidden, but the usual answer, the gross, is copied into SalariedEmployee and into every future kind of worker that follows it. That brings back the copies this design is meant to remove.
A hook with the usual answerOur pick
The base class returns the gross, and only the workers that differ override it. Salaried staff write nothing. The cost is that a new kind of worker gets the default without being asked, so a contractor-like worker who forgets to override it would quietly pay into the provident fund. The rule we follow: a step with one usual answer is a hook, and a step with no usual answer is abstract.
Step 3: hooks with a default
These are the three hooks. Each one has a body, which is the default:
// Hooks: a default that a worker type may replace. protected long providentFundWages(long gross) { return gross; } protected long taxDeducted(long gross) { return 0; } protected List<String> slipNotes(WorkMonth month) { return List.of(); }Contractors override all three: no provident fund, tax deducted at source, and a note with their hours. Here are the first two:
// Contractors are not on the provident fund. @Override protected long providentFundWages(long gross) { return 0; } @Override protected long taxDeducted(long gross) { return percentOf(gross, TAX_DEDUCTED_PERCENT); }Sales staff override the provident fund wage, so that the fund is worked out on the base salary only:
// The provident fund is on the base salary only, never on commission. @Override protected long providentFundWages(long gross) { return baseSalary; }The 12% rate and the $180 cap stay in Worker, in a private step. The hook only answers one question: which wage is the fund worked out on? For Meera that wage is her $1,200 base salary, so her fund is $144. On her gross of $1,937 the default would have given the full $180.
A hook that answers one question is safer than a hook that replaces a whole step. If sales staff overrode the whole provident fund step, they would have to call super with their base salary to reuse the 12% rule and the cap, and that override would depend on what the base version does inside. Even so, a hook is never completely safe, as What it costs shows.
Step 4: the fixed steps stay private
The provident fund rule, professional tax, rounding and the checks are the same for everyone, so they are private. A subclass cannot override them and cannot call them:
// Fixed steps: private, so no worker type can change them. private long providentFund(long wages) { return Math.min(percentOf(wages, PROVIDENT_FUND_PERCENT), PROVIDENT_FUND_CAP); } private long professionalTax(long gross) { return gross > PROFESSIONAL_TAX_ABOVE ? PROFESSIONAL_TAX : 0; } private void addDeduction(List<Deduction> deductions, String label, long cents, long gross) { long amount = toWholeDollars(cents); if (amount > gross) { throw new IllegalStateException(label + " of " + amount + " cents is more than the gross for " + id); } if (amount > 0) { deductions.add(new Deduction(label, amount)); } } // Every amount on a slip is whole dollars; half a dollar rounds up. private long toWholeDollars(long cents) { if (cents < 0) { throw new IllegalStateException("A pay step returned a negative amount for " + id + ": " + cents); } return Math.addExact(cents, 50) / 100 * 100; }The template also checks what the subclasses give it. A hook that returns a deduction bigger than the gross (line 91) or a negative amount (line 101) is refused with an IllegalStateException that names the step. These are bugs in a subclass, not bad data, and the base class is the one place that can catch them for every kind of worker at once.
Should the steps be public, protected or private?
Public steps
Any code could call worker.taxDeducted(gross) on its own, outside the template. Then a report somewhere might work out tax deducted at source without the rounding, and the order the template protects would mean nothing.
Protected steps, private fixed stepsOur pick
Subclasses can override the abstract steps and the hooks, which is their job. Code outside the hierarchy and outside the payroll package can call only payFor, id and name. Worker sits in the payroll package and the workers in workers, so the payroll run in run cannot reach the steps either. The steps that must not change are private, which keeps them away from subclasses too.
Each worker class is also final. A subclass of Contractor could override the same hooks again, and the chain of overrides would get hard to follow. One level of subclass is enough here.
Step 5: paying everyone
PayrollRun pays every worker for one month. It does not know which kinds of worker exist. It calls payFor on each one:
List<PaySlip> slips = new ArrayList<>(); List<PayrollResult.Failure> failures = new ArrayList<>(); for (Map.Entry<Worker, WorkMonth> entry : monthByWorker.entrySet()) { // One worker's bad record must not stop everyone else's pay. try { slips.add(entry.getKey().payFor(entry.getValue())); } catch (RuntimeException e) { failures.add(new PayrollResult.Failure(entry.getKey().id(), e)); } } return new PayrollResult(slips, failures);Before this loop, run refuses a map with the same worker id twice, or a work month for the wrong month, with an IllegalArgumentException. Those are mistakes in the input as a whole, so nobody is paid until they are fixed.
Inside the loop, one worker's slip can still fail: a commission so large that it overflows, or a bug in a subclass's hook. The run records the worker's id and the exception, and goes on to the next worker. One bad record should not stop everyone else's pay. Finance sees the failures in the result and fixes them separately.
The finished design
Here is one contractor's slip, traced through the code. The base class and the subclass are one object, so the figure shows them as two columns of the same object:
The whole project is below. Click any class name to open its file.
package payroll; import java.util.ArrayList;import java.util.List;import java.util.Objects; public abstract class Worker { private static final int PROVIDENT_FUND_PERCENT = 12; private static final long PROVIDENT_FUND_CAP = 180_00; private static final long PROFESSIONAL_TAX = 20_00; private static final long PROFESSIONAL_TAX_ABOVE = 1_500_00; private final String id; private final String name; protected Worker(String id, String name) { this.id = requireText(id, "id"); this.name = requireText(name, "name"); } public final String id() { return id; } public final String name() { return name; } // The template method: the steps and their order are written here once, and final keeps them here. public final PaySlip payFor(WorkMonth month) { Objects.requireNonNull(month, "month"); long gross = toWholeDollars(grossPay(month)); List<Deduction> deductions = new ArrayList<>(); addDeduction(deductions, "Provident fund", providentFund(providentFundWages(gross)), gross); addDeduction(deductions, "Professional tax", professionalTax(gross), gross); addDeduction(deductions, "Tax deducted at source", taxDeducted(gross), gross); long totalDeducted = 0; for (Deduction deduction : deductions) { totalDeducted = Math.addExact(totalDeducted, deduction.amount()); } if (totalDeducted > gross) { throw new IllegalStateException("Deductions of " + totalDeducted + " cents exceed the gross of " + gross + " for " + id); } return new PaySlip(id, name, payType(), month.month(), gross, deductions, gross - totalDeducted, slipNotes(month)); } // Steps every worker type must write. protected abstract long grossPay(WorkMonth month); protected abstract String payType(); // Hooks: a default that a worker type may replace. protected long providentFundWages(long gross) { return gross; } protected long taxDeducted(long gross) { return 0; } protected List<String> slipNotes(WorkMonth month) { return List.of(); } // Helpers for the worker types. protected static long percentOf(long amount, int percent) { return Math.multiplyExact(amount, percent) / 100; } protected static String dollars(long cents) { return PaySlip.dollars(cents); } // Fixed steps: private, so no worker type can change them. private long providentFund(long wages) { return Math.min(percentOf(wages, PROVIDENT_FUND_PERCENT), PROVIDENT_FUND_CAP); } private long professionalTax(long gross) { return gross > PROFESSIONAL_TAX_ABOVE ? PROFESSIONAL_TAX : 0; } private void addDeduction(List<Deduction> deductions, String label, long cents, long gross) { long amount = toWholeDollars(cents); if (amount > gross) { throw new IllegalStateException(label + " of " + amount + " cents is more than the gross for " + id); } if (amount > 0) { deductions.add(new Deduction(label, amount)); } } // Every amount on a slip is whole dollars; half a dollar rounds up. private long toWholeDollars(long cents) { if (cents < 0) { throw new IllegalStateException("A pay step returned a negative amount for " + id + ": " + cents); } return Math.addExact(cents, 50) / 100 * 100; } private static String requireText(String value, String what) { Objects.requireNonNull(value, what); if (value.isBlank()) { throw new IllegalArgumentException("A worker's " + what + " cannot be blank"); } return value; }}The demo pays all three workers for March 2026:
W-1 Asha Rao (Salaried), March 2026 Gross pay $6,000 Provident fund -$180 Professional tax -$20 Net pay $5,800 W-2 Ravi Kumar (Contractor), March 2026 Gross pay $8,282 Professional tax -$20 Tax deducted at source -$828 Net pay $7,434 162 h 23 min at $51 an hour W-3 Meera Iyer (Sales), March 2026 Gross pay $1,937 Provident fund -$144 Professional tax -$20 Net pay $1,773 Commission: 5% of $14,735 above the $20,000 target 3 slips, 0 failures
Compare it with the first version's output. Ravi's gross is $8,282 now, because rounding is one rule in one place: 162 hours 23 minutes at $51 an hour is $8,281.55, which rounds up. His tax deducted is 10% of that, $828. Meera's slip lists the provident fund first, like everyone else's, and her provident fund is $144 on her base salary. No slip failed, so the run reports 0 failures.
What it costs
The pattern makes one kind of change cheap and another kind risky.
Changing a shared rule is cheap. Rounding, professional tax and the order of the deductions each live in one place. A new rule for everyone, such as a $5 welfare fund deduction for all workers, is one new private step in Worker and one new line in payFor. In the first version it was three edits, and the bugs above show what happens when one is missed.
Adding a kind of worker is cheap too. An intern on a fixed stipend is one new subclass that writes grossPay and payType, plus whichever hooks differ.
Changing a fixed step can catch a hook out. Every subclass that overrides a hook depends on how the base class uses its answer. Suppose the company adds a rule: no provident fund for anyone whose gross is below $1,500. Someone writes it inside the private providentFund step as "no fund when the wages are below $1,500", because for most workers the wages are the gross. Salaried staff get the intended result, because their wages are their gross. Contractors' wages are 0 anyway. Meera's wages are her $1,200 base salary, so she loses her provident fund, although her gross of $1,937 is above the limit. Everything compiles, and a test that uses only salaried workers passes. This is called the fragile base class problem: subclasses depend on details of the base class that its method signatures do not show.
There are two ways to keep the base class from becoming fragile. Keep the hooks few, each with a one-line note of what it receives, what it must return, and how the base class uses the answer. And let the base class check what comes back, as addDeduction does: a wrong answer then fails loudly instead of printing a wrong slip.
When the pattern is too much
If two kinds of worker differ only in their numbers, they are one class with different data. A part-time employee on half a salary is a SalariedEmployee with a smaller salary, not a new subclass.
If the steps vary independently of each other, subclasses multiply. Suppose gross pay has three rules, the provident fund two and tax deducted two. Covering every mix with subclasses takes twelve classes. Separate rule objects for each step need only seven, combined when each worker is built:
public PaySlip payFor(WorkMonth month) { long gross = toWholeDollars(grossRule.grossPay(month)); List<Deduction> deductions = new ArrayList<>(); addDeduction(deductions, "Provident fund", providentFundRule.amount(gross), gross); addDeduction(deductions, "Professional tax", professionalTax(gross), gross); addDeduction(deductions, "Tax deducted at source", taxRule.amount(gross), gross); return slipFrom(gross, deductions, month);}The order is still fixed in one method, but the varying steps are now objects passed in, not subclasses. That is Strategy, used for each step.
We would also skip the pattern when there is only one kind of worker. A template with one subclass is a class split in two for no reason.
Template Method or Strategy?
Both let one part of a job vary. The Strategy pattern page builds a checkout whose shipping options are interchangeable objects. The difference is how the varying part gets in.
| Template Method | Strategy | |
|---|---|---|
| How the varying part is supplied | A subclass overrides a step | An object is passed in |
| When the choice is made | When the class is written | When the object is built, or later |
| Who owns the order of the steps | The base class, in a final method | The context that calls the strategy |
| Can two choices be mixed freely | No: each mix needs a subclass | Yes: pass in any combination |
| Example | Pay slips for three kinds of worker | Shipping options at a checkout |
A short way to say it: Template Method varies steps by inheritance, decided when the class is written. Strategy varies them by passing in an object, which the client can choose when it builds the context.
Other pages on this site use the pattern in small ways. The Chain of Responsibility page uses it so that every handler follows the same "decide, or pass on" steps. The Decorator and Factory pages explain why they do not. Factory Method is a close relative: a base class with fixed steps that leaves creating one object to its subclasses.
In an interview
The pattern fits wherever a process has fixed steps and a few that vary by type: pay slips and invoices, data imports (read, check, convert, save), report generation, game turns, and approval flows. The Java library uses it too. AbstractList builds indexOf, contains and its iterator on top of two methods a subclass writes, get and size. InputStream.read(byte[], int, int) is written in terms of the single-byte read() that each stream supplies. These library methods are not final, so a subclass may replace them with a faster version.
Present it in this order:
- Draw the table of steps and types first. Mark which steps vary and which never do. That table is the design.
- Write the base class with the final template method. Say which steps are abstract, which are hooks and which are private, and why.
- Write one subclass in full, and one hook override. Then say what a new kind of worker costs: one subclass.
Mistakes to avoid:
- A template method that is not final. A subclass can then reorder or skip steps, and the base class guarantees nothing.
- Public steps. Code outside the hierarchy can call one step on its own and skip the rules around it.
- Calling an overridable method from the base class constructor. The subclass's fields are not set yet when the base constructor runs, so the override sees zeros and nulls.
Worker's constructor only checks its own fields. - A hook that must call
super. If an override only works when it remembers to call the base version first, that rule lives in nobody's code. Split the step so the base class does its part in the template itself. - Too many hooks. Every hook is a promise about when it is called and with what. A base class with ten hooks is hard to change without breaking a subclass.
Summary
- Use Template Method when several classes follow the same steps in the same order and differ in only a few steps.
- Draw the table of steps and types first, and mark which steps vary.
- The base class runs the steps in one final method. Shared steps are private, steps with no default are abstract, and steps with a default are hooks.
- A shared rule changes in one place. A new kind of worker is one subclass.
- A change inside a fixed step can still break a subclass that overrides a hook, and the compiler does not check it.
- When steps vary independently, pass in an object for each step instead: that is Strategy.