Template Method: Same Routine, Your Own Step

When three label classes copy the same four steps and differ only in the barcode, a fix to the shared steps has to be made three times, and one copy is always missed; writing the routine once in a base class and letting each carrier's subclass fill in its own barcode is the Template Method pattern.

Journeyman · OOP · Updated

By

After this lesson you can

  • Write the steps once in a base class and let each subclass fill in the one step that differs
  • Spot the smells that point to Template Method: sibling classes that copy the same steps and differ in one

Key takeaways

  • The smell: sibling classes that copy the same steps, in the same order, and differ in one of them.
  • The cause: the routine has no home of its own, so every class keeps a copy, and the copies drift apart.
  • The fix: the routine is written once in a base class, and the step that differs is an abstract method each subclass fills in.
  • A fix to the shared steps is made once, and every carrier's label gets it.
  • Handing the step in as a function does the same job without a subclass, which is the next lesson's question.

Before this: Strategy: When the Rule Needs a Class of Its Own, which met the three carriers, and Inheritance and Composition: Is-a and Has-a, where a subclass fills in what its parent leaves open.

Every package needs a label before it leaves the depot, and every carrier wants the same four things on it, in the same order: the address, a barcode, the rate, and then the label is printed. Only the barcode differs: QuickShip prints QS-0042, EcoFreight ECO42, SameDay SD/42. Three carriers, one routine, one step different. This lesson follows what happened when each carrier got its own copy of the routine, and ends with a pattern called Template Method.

The symptom: three copies of one routine

Each carrier's label is its own class. Last month the depot asked for the recipient's name on every label, above the street:

Package parcel = new Package(42, "Maya", "Oak Ave");
Console.WriteLine(new QuickShipLabel().Make(parcel, 900));
Console.WriteLine(new EcoFreightLabel().Make(parcel, 770));
Console.WriteLine(new SameDayLabel().Make(parcel, 1500));

record Package(int Id, string Recipient, string Street);

class QuickShipLabel
{
    public string Make(Package parcel, int cents)
    {
        string address = quot;To: {parcel.Recipient}, {parcel.Street}";
        string barcode = quot;QS-{parcel.Id:D4}";
        string rate = quot;${cents / 100}.{cents % 100:D2}";
        return quot;QuickShip | {address} | {barcode} | {rate}";
    }
}

class EcoFreightLabel
{
    public string Make(Package parcel, int cents)
    {
        string address = quot;To: {parcel.Recipient}, {parcel.Street}";
        string barcode = quot;ECO{parcel.Id}";
        string rate = quot;${cents / 100}.{cents % 100:D2}";
        return quot;EcoFreight | {address} | {barcode} | {rate}";
    }
}

class SameDayLabel
{
    public string Make(Package parcel, int cents)
    {
        string address = quot;To: {parcel.Street}";
        string barcode = quot;SD/{parcel.Id}";
        string rate = quot;${cents / 100}.{cents % 100:D2}";
        return quot;SameDay | {address} | {barcode} | {rate}";
    }
}
QuickShip | To: Maya, Oak Ave | QS-0042 | $9.00
EcoFreight | To: Maya, Oak Ave | ECO42 | $7.70
SameDay | To: Oak Ave | SD/42 | $15.00
record Package(int id, String recipient, String street) {}

class QuickShipLabel {
    String make(Package parcel, int cents) {
        String address = "To: " + parcel.recipient() + ", " + parcel.street();
        String barcode = String.format("QS-%04d", parcel.id());
        String rate = "quot; + cents / 100 + "." + String.format("%02d", cents % 100);
        return "QuickShip | " + address + " | " + barcode + " | " + rate;
    }
}

class EcoFreightLabel {
    String make(Package parcel, int cents) {
        String address = "To: " + parcel.recipient() + ", " + parcel.street();
        String barcode = "ECO" + parcel.id();
        String rate = "quot; + cents / 100 + "." + String.format("%02d", cents % 100);
        return "EcoFreight | " + address + " | " + barcode + " | " + rate;
    }
}

class SameDayLabel {
    String make(Package parcel, int cents) {
        String address = "To: " + parcel.street();
        String barcode = "SD/" + parcel.id();
        String rate = "quot; + cents / 100 + "." + String.format("%02d", cents % 100);
        return "SameDay | " + address + " | " + barcode + " | " + rate;
    }
}

void main() {
    Package parcel = new Package(42, "Maya", "Oak Ave");
    IO.println(new QuickShipLabel().make(parcel, 900));
    IO.println(new EcoFreightLabel().make(parcel, 770));
    IO.println(new SameDayLabel().make(parcel, 1500));
}
QuickShip | To: Maya, Oak Ave | QS-0042 | $9.00
EcoFreight | To: Maya, Oak Ave | ECO42 | $7.70
SameDay | To: Oak Ave | SD/42 | $15.00
class Package:
    def __init__(self, id, recipient, street):
        self.id = id
        self.recipient = recipient
        self.street = street


class QuickShipLabel:
    def make(self, parcel, cents):
        address = f"To: {parcel.recipient}, {parcel.street}"
        barcode = f"QS-{parcel.id:04d}"
        rate = f"${cents // 100}.{cents % 100:02d}"
        return f"QuickShip | {address} | {barcode} | {rate}"


class EcoFreightLabel:
    def make(self, parcel, cents):
        address = f"To: {parcel.recipient}, {parcel.street}"
        barcode = f"ECO{parcel.id}"
        rate = f"${cents // 100}.{cents % 100:02d}"
        return f"EcoFreight | {address} | {barcode} | {rate}"


class SameDayLabel:
    def make(self, parcel, cents):
        address = f"To: {parcel.street}"
        barcode = f"SD/{parcel.id}"
        rate = f"${cents // 100}.{cents % 100:02d}"
        return f"SameDay | {address} | {barcode} | {rate}"


parcel = Package(42, "Maya", "Oak Ave")
print(QuickShipLabel().make(parcel, 900))
print(EcoFreightLabel().make(parcel, 770))
print(SameDayLabel().make(parcel, 1500))
QuickShip | To: Maya, Oak Ave | QS-0042 | $9.00
EcoFreight | To: Maya, Oak Ave | ECO42 | $7.70
SameDay | To: Oak Ave | SD/42 | $15.00
class Package {
  constructor(id, recipient, street) {
    this.id = id;
    this.recipient = recipient;
    this.street = street;
  }
}

class QuickShipLabel {
  make(parcel, cents) {
    const address = `To: ${parcel.recipient}, ${parcel.street}`;
    const barcode = `QS-${String(parcel.id).padStart(4, "0")}`;
    const rate = `${Math.floor(cents / 100)}.${String(cents % 100).padStart(2, "0")}`;
    return `QuickShip | ${address} | ${barcode} | ${rate}`;
  }
}

class EcoFreightLabel {
  make(parcel, cents) {
    const address = `To: ${parcel.recipient}, ${parcel.street}`;
    const barcode = `ECO${parcel.id}`;
    const rate = `${Math.floor(cents / 100)}.${String(cents % 100).padStart(2, "0")}`;
    return `EcoFreight | ${address} | ${barcode} | ${rate}`;
  }
}

class SameDayLabel {
  make(parcel, cents) {
    const address = `To: ${parcel.street}`;
    const barcode = `SD/${parcel.id}`;
    const rate = `${Math.floor(cents / 100)}.${String(cents % 100).padStart(2, "0")}`;
    return `SameDay | ${address} | ${barcode} | ${rate}`;
  }
}

const parcel = new Package(42, "Maya", "Oak Ave");
console.log(new QuickShipLabel().make(parcel, 900));
console.log(new EcoFreightLabel().make(parcel, 770));
console.log(new SameDayLabel().make(parcel, 1500));
QuickShip | To: Maya, Oak Ave | QS-0042 | $9.00
EcoFreight | To: Maya, Oak Ave | ECO42 | $7.70
SameDay | To: Oak Ave | SD/42 | $15.00
class Package {
  id: number;
  recipient: string;
  street: string;

  constructor(id: number, recipient: string, street: string) {
    this.id = id;
    this.recipient = recipient;
    this.street = street;
  }
}

class QuickShipLabel {
  make(parcel: Package, cents: number): string {
    const address = `To: ${parcel.recipient}, ${parcel.street}`;
    const barcode = `QS-${String(parcel.id).padStart(4, "0")}`;
    const rate = `${Math.floor(cents / 100)}.${String(cents % 100).padStart(2, "0")}`;
    return `QuickShip | ${address} | ${barcode} | ${rate}`;
  }
}

class EcoFreightLabel {
  make(parcel: Package, cents: number): string {
    const address = `To: ${parcel.recipient}, ${parcel.street}`;
    const barcode = `ECO${parcel.id}`;
    const rate = `${Math.floor(cents / 100)}.${String(cents % 100).padStart(2, "0")}`;
    return `EcoFreight | ${address} | ${barcode} | ${rate}`;
  }
}

class SameDayLabel {
  make(parcel: Package, cents: number): string {
    const address = `To: ${parcel.street}`;
    const barcode = `SD/${parcel.id}`;
    const rate = `${Math.floor(cents / 100)}.${String(cents % 100).padStart(2, "0")}`;
    return `SameDay | ${address} | ${barcode} | ${rate}`;
  }
}

const parcel = new Package(42, "Maya", "Oak Ave");
console.log(new QuickShipLabel().make(parcel, 900));
console.log(new EcoFreightLabel().make(parcel, 770));
console.log(new SameDayLabel().make(parcel, 1500));
QuickShip | To: Maya, Oak Ave | QS-0042 | $9.00
EcoFreight | To: Maya, Oak Ave | ECO42 | $7.70
SameDay | To: Oak Ave | SD/42 | $15.00

SameDay's label has no name on it. Two copies of the routine got the change and the third didn't, and the driver at Oak Ave has to guess who the package is for.

  • The symptom: three classes that copy the same steps (address, rate, print), in the same order, and differ in one (the barcode).
  • The cause: the routine has no home of its own. Each class keeps a copy, so every fix to a shared step is three fixes, and the copies drift apart.

What would you try?

Make the change in all three, carefully. That fixes today's label. The depot's next request (a "fragile" stamp, a bigger font for the street) is three edits again, and a fourth carrier makes it four.

One label class with an if on the carrier's name for the barcode. The routine is written once now, which is good. But the barcode if grows with every carrier, and the label class has to know them all, which is the switch from the last lesson in a new place.

Copy-paste a "master" label and keep the others in step by hand. That's what the code above is. Copies don't stay in step.

What would really help: write the routine once, in one place, with a gap where the barcode goes, and let each carrier fill in only that gap.

The everyday version: a workout plan

A gym's group class hands everyone the same workout card: warm up for ten minutes, then your own main set, then cool down for five. One person rows, one runs, one cycles. The plan is the same for everyone and in the same order; each person fills in the middle.

A gym's workout card pinned to a wall, with three lines, "Warm up: 10 minutes", "Main set: your choice" and "Cool down: 5 minutes", and below it three people at the same moment of their main set: one rowing, one running on a treadmill, one cycling

The fix: write the routine once

The routine moves into a base class, Label. Its Make method runs the four steps, in order, and three of them are written right there. The barcode step is abstract: a method with no body, which every subclass must fill in. Each carrier's label is now a subclass with one job:

Template Method's roles: the routine, written once, runs four steps (address, barcode, rate, print). Only step 2, the barcode, is filled in by each carrier's label, QS-0042, ECO42 or SD/42; each label is a kind of the routine, inside a dashed fence labeled "what changes: the barcode"

How it got its name

A method that lays out the steps of a routine and leaves one or more of them for subclasses to fill in is a template method: the base class is the template, and each subclass fills in the blanks. The pattern, Template Method, is in the original 1994 book. A step the base class leaves open is usually an abstract method; a step it gives a default for, which subclasses may change, is called a hook in your textbook.

The classic version

Package parcel = new Package(42, "Maya", "Oak Ave");
Console.WriteLine(new QuickShipLabel().Make(parcel, 900));
Console.WriteLine(new EcoFreightLabel().Make(parcel, 770));
Console.WriteLine(new SameDayLabel().Make(parcel, 1500));

record Package(int Id, string Recipient, string Street);

abstract class Label
{
    // The routine, written once: address, barcode, rate, print.
    public string Make(Package parcel, int cents) => Print(Address(parcel), Barcode(parcel), Rate(cents));

    // The two things each carrier fills in: its name, and its barcode.
    protected abstract string Carrier { get; }
    protected abstract string Barcode(Package parcel);

    private string Address(Package parcel) => quot;To: {parcel.Recipient}, {parcel.Street}";
    private string Rate(int cents) => quot;${cents / 100}.{cents % 100:D2}";
    private string Print(string address, string barcode, string rate) => quot;{Carrier} | {address} | {barcode} | {rate}";
}

class QuickShipLabel : Label
{
    protected override string Carrier => "QuickShip";
    protected override string Barcode(Package parcel) => quot;QS-{parcel.Id:D4}";
}

class EcoFreightLabel : Label
{
    protected override string Carrier => "EcoFreight";
    protected override string Barcode(Package parcel) => quot;ECO{parcel.Id}";
}

class SameDayLabel : Label
{
    protected override string Carrier => "SameDay";
    protected override string Barcode(Package parcel) => quot;SD/{parcel.Id}";
}
QuickShip | To: Maya, Oak Ave | QS-0042 | $9.00
EcoFreight | To: Maya, Oak Ave | ECO42 | $7.70
SameDay | To: Maya, Oak Ave | SD/42 | $15.00
record Package(int id, String recipient, String street) {}

abstract class Label {
    // The routine, written once: address, barcode, rate, print. final: no subclass can change the order.
    final String make(Package parcel, int cents) { return print(address(parcel), barcode(parcel), rate(cents)); }

    // The two things each carrier fills in: its name, and its barcode.
    abstract String carrier();
    abstract String barcode(Package parcel);

    private String address(Package parcel) { return "To: " + parcel.recipient() + ", " + parcel.street(); }
    private String rate(int cents) { return "quot; + cents / 100 + "." + String.format("%02d", cents % 100); }
    private String print(String address, String barcode, String rate) { return carrier() + " | " + address + " | " + barcode + " | " + rate; }
}

class QuickShipLabel extends Label {
    String carrier() { return "QuickShip"; }
    String barcode(Package parcel) { return String.format("QS-%04d", parcel.id()); }
}

class EcoFreightLabel extends Label {
    String carrier() { return "EcoFreight"; }
    String barcode(Package parcel) { return "ECO" + parcel.id(); }
}

class SameDayLabel extends Label {
    String carrier() { return "SameDay"; }
    String barcode(Package parcel) { return "SD/" + parcel.id(); }
}

void main() {
    Package parcel = new Package(42, "Maya", "Oak Ave");
    IO.println(new QuickShipLabel().make(parcel, 900));
    IO.println(new EcoFreightLabel().make(parcel, 770));
    IO.println(new SameDayLabel().make(parcel, 1500));
}
QuickShip | To: Maya, Oak Ave | QS-0042 | $9.00
EcoFreight | To: Maya, Oak Ave | ECO42 | $7.70
SameDay | To: Maya, Oak Ave | SD/42 | $15.00
from abc import ABC, abstractmethod


class Package:
    def __init__(self, id, recipient, street):
        self.id = id
        self.recipient = recipient
        self.street = street


class Label(ABC):
    carrier = ""

    def make(self, parcel, cents):
        """The routine, written once: address, barcode, rate, print."""
        return self._print(self._address(parcel), self.barcode(parcel), self._rate(cents))

    @abstractmethod
    def barcode(self, parcel):
        """The one step each carrier fills in."""

    def _address(self, parcel):
        return f"To: {parcel.recipient}, {parcel.street}"

    def _rate(self, cents):
        return f"${cents // 100}.{cents % 100:02d}"

    def _print(self, address, barcode, rate):
        return f"{self.carrier} | {address} | {barcode} | {rate}"


class QuickShipLabel(Label):
    carrier = "QuickShip"

    def barcode(self, parcel):
        return f"QS-{parcel.id:04d}"


class EcoFreightLabel(Label):
    carrier = "EcoFreight"

    def barcode(self, parcel):
        return f"ECO{parcel.id}"


class SameDayLabel(Label):
    carrier = "SameDay"

    def barcode(self, parcel):
        return f"SD/{parcel.id}"


parcel = Package(42, "Maya", "Oak Ave")
print(QuickShipLabel().make(parcel, 900))
print(EcoFreightLabel().make(parcel, 770))
print(SameDayLabel().make(parcel, 1500))
QuickShip | To: Maya, Oak Ave | QS-0042 | $9.00
EcoFreight | To: Maya, Oak Ave | ECO42 | $7.70
SameDay | To: Maya, Oak Ave | SD/42 | $15.00
class Package {
  constructor(id, recipient, street) {
    this.id = id;
    this.recipient = recipient;
    this.street = street;
  }
}

class Label {
  // The routine, written once: address, barcode, rate, print.
  make(parcel, cents) {
    return this.#print(this.#address(parcel), this.barcode(parcel), this.#rate(cents));
  }

  // The one step each carrier fills in.
  barcode(parcel) {
    throw new Error("Each carrier's label makes its own barcode");
  }

  #address(parcel) { return `To: ${parcel.recipient}, ${parcel.street}`; }
  #rate(cents) { return `${Math.floor(cents / 100)}.${String(cents % 100).padStart(2, "0")}`; }
  #print(address, barcode, rate) { return `${this.carrier} | ${address} | ${barcode} | ${rate}`; }
}

class QuickShipLabel extends Label {
  carrier = "QuickShip";
  barcode(parcel) { return `QS-${String(parcel.id).padStart(4, "0")}`; }
}

class EcoFreightLabel extends Label {
  carrier = "EcoFreight";
  barcode(parcel) { return `ECO${parcel.id}`; }
}

class SameDayLabel extends Label {
  carrier = "SameDay";
  barcode(parcel) { return `SD/${parcel.id}`; }
}

const parcel = new Package(42, "Maya", "Oak Ave");
console.log(new QuickShipLabel().make(parcel, 900));
console.log(new EcoFreightLabel().make(parcel, 770));
console.log(new SameDayLabel().make(parcel, 1500));
QuickShip | To: Maya, Oak Ave | QS-0042 | $9.00
EcoFreight | To: Maya, Oak Ave | ECO42 | $7.70
SameDay | To: Maya, Oak Ave | SD/42 | $15.00
class Package {
  id: number;
  recipient: string;
  street: string;

  constructor(id: number, recipient: string, street: string) {
    this.id = id;
    this.recipient = recipient;
    this.street = street;
  }
}

abstract class Label {
  // The two things each carrier fills in: its name, and its barcode.
  abstract carrier: string;
  abstract barcode(parcel: Package): string;

  // The routine, written once: address, barcode, rate, print.
  make(parcel: Package, cents: number): string {
    return this.print(this.address(parcel), this.barcode(parcel), this.rate(cents));
  }

  private address(parcel: Package): string { return `To: ${parcel.recipient}, ${parcel.street}`; }
  private rate(cents: number): string { return `${Math.floor(cents / 100)}.${String(cents % 100).padStart(2, "0")}`; }
  private print(address: string, barcode: string, rate: string): string { return `${this.carrier} | ${address} | ${barcode} | ${rate}`; }
}

class QuickShipLabel extends Label {
  carrier = "QuickShip";
  barcode(parcel: Package): string { return `QS-${String(parcel.id).padStart(4, "0")}`; }
}

class EcoFreightLabel extends Label {
  carrier = "EcoFreight";
  barcode(parcel: Package): string { return `ECO${parcel.id}`; }
}

class SameDayLabel extends Label {
  carrier = "SameDay";
  barcode(parcel: Package): string { return `SD/${parcel.id}`; }
}

const parcel = new Package(42, "Maya", "Oak Ave");
console.log(new QuickShipLabel().make(parcel, 900));
console.log(new EcoFreightLabel().make(parcel, 770));
console.log(new SameDayLabel().make(parcel, 1500));
QuickShip | To: Maya, Oak Ave | QS-0042 | $9.00
EcoFreight | To: Maya, Oak Ave | ECO42 | $7.70
SameDay | To: Maya, Oak Ave | SD/42 | $15.00

SameDay's label has Maya's name now, and nobody touched SameDayLabel to get it: the address step lives in one place, so it's right for everyone. The depot's next request, a "fragile" stamp, is one new step in Make, made once. A fourth carrier is a subclass with a name and a barcode, and nothing else.

Where the languages differ. C#, Java and TypeScript mark the barcode step abstract, so a subclass that forgets it doesn't compile. Python's ABC and @abstractmethod stop you from making a label without a barcode, when the program runs. JavaScript has no abstract methods, so the base class's barcode throws a clear error instead. Java marks make final, so no subclass can change the order of the steps; C# methods can't be overridden unless they're marked virtual, so Make is safe already.

Here is SameDay's label being made, as a sequence diagram. Notice that every call but one goes from the label to itself, to steps written once in Label; only the barcode is SameDay's own:

A sequence diagram of making SameDay's label: the printer calls make(parcel, 1500), and the label calls its own steps in order: address, barcode, rate, print. Only barcode is SameDay's own; the rest are written once in Label. The reply is SameDay's printed label

The modern version: hand the step in

Many teams now write the same routine without a subclass: one Label class, handed the carrier's name and its barcode step as a function. The routine is still written once, and each carrier still fills in one step:

Package parcel = new Package(42, "Maya", "Oak Ave");
Label quickShip = new Label("QuickShip", parcel => quot;QS-{parcel.Id:D4}");
Label ecoFreight = new Label("EcoFreight", parcel => quot;ECO{parcel.Id}");
Label sameDay = new Label("SameDay", parcel => quot;SD/{parcel.Id}");
Console.WriteLine(quickShip.Make(parcel, 900));
Console.WriteLine(ecoFreight.Make(parcel, 770));
Console.WriteLine(sameDay.Make(parcel, 1500));

record Package(int Id, string Recipient, string Street);

class Label
{
    private readonly string carrier;
    private readonly Func<Package, string> barcode;
    public Label(string carrier, Func<Package, string> barcode) { this.carrier = carrier; this.barcode = barcode; }

    // The routine, written once; the barcode step is the function this label was handed.
    public string Make(Package parcel, int cents)
    {
        string address = quot;To: {parcel.Recipient}, {parcel.Street}";
        string rate = quot;${cents / 100}.{cents % 100:D2}";
        return quot;{carrier} | {address} | {barcode(parcel)} | {rate}";
    }
}
QuickShip | To: Maya, Oak Ave | QS-0042 | $9.00
EcoFreight | To: Maya, Oak Ave | ECO42 | $7.70
SameDay | To: Maya, Oak Ave | SD/42 | $15.00
record Package(int id, String recipient, String street) {}

class Label {
    String carrier;
    Function<Package, String> barcode;
    Label(String carrier, Function<Package, String> barcode) { this.carrier = carrier; this.barcode = barcode; }

    // The routine, written once; the barcode step is the function this label was handed.
    String make(Package parcel, int cents) {
        String address = "To: " + parcel.recipient() + ", " + parcel.street();
        String rate = "quot; + cents / 100 + "." + String.format("%02d", cents % 100);
        return carrier + " | " + address + " | " + barcode.apply(parcel) + " | " + rate;
    }
}

void main() {
    Package parcel = new Package(42, "Maya", "Oak Ave");
    Label quickShip = new Label("QuickShip", p -> String.format("QS-%04d", p.id()));
    Label ecoFreight = new Label("EcoFreight", p -> "ECO" + p.id());
    Label sameDay = new Label("SameDay", p -> "SD/" + p.id());
    IO.println(quickShip.make(parcel, 900));
    IO.println(ecoFreight.make(parcel, 770));
    IO.println(sameDay.make(parcel, 1500));
}
QuickShip | To: Maya, Oak Ave | QS-0042 | $9.00
EcoFreight | To: Maya, Oak Ave | ECO42 | $7.70
SameDay | To: Maya, Oak Ave | SD/42 | $15.00
class Package:
    def __init__(self, id, recipient, street):
        self.id = id
        self.recipient = recipient
        self.street = street


class Label:
    def __init__(self, carrier, barcode):
        self.carrier = carrier
        self.barcode = barcode

    def make(self, parcel, cents):
        """The routine, written once; the barcode step is the function this label was handed."""
        address = f"To: {parcel.recipient}, {parcel.street}"
        rate = f"${cents // 100}.{cents % 100:02d}"
        return f"{self.carrier} | {address} | {self.barcode(parcel)} | {rate}"


parcel = Package(42, "Maya", "Oak Ave")
quick_ship = Label("QuickShip", lambda p: f"QS-{p.id:04d}")
eco_freight = Label("EcoFreight", lambda p: f"ECO{p.id}")
same_day = Label("SameDay", lambda p: f"SD/{p.id}")
print(quick_ship.make(parcel, 900))
print(eco_freight.make(parcel, 770))
print(same_day.make(parcel, 1500))
QuickShip | To: Maya, Oak Ave | QS-0042 | $9.00
EcoFreight | To: Maya, Oak Ave | ECO42 | $7.70
SameDay | To: Maya, Oak Ave | SD/42 | $15.00
class Package {
  constructor(id, recipient, street) {
    this.id = id;
    this.recipient = recipient;
    this.street = street;
  }
}

class Label {
  constructor(carrier, barcode) {
    this.carrier = carrier;
    this.barcode = barcode;
  }

  // The routine, written once; the barcode step is the function this label was handed.
  make(parcel, cents) {
    const address = `To: ${parcel.recipient}, ${parcel.street}`;
    const rate = `${Math.floor(cents / 100)}.${String(cents % 100).padStart(2, "0")}`;
    return `${this.carrier} | ${address} | ${this.barcode(parcel)} | ${rate}`;
  }
}

const parcel = new Package(42, "Maya", "Oak Ave");
const quickShip = new Label("QuickShip", (p) => `QS-${String(p.id).padStart(4, "0")}`);
const ecoFreight = new Label("EcoFreight", (p) => `ECO${p.id}`);
const sameDay = new Label("SameDay", (p) => `SD/${p.id}`);
console.log(quickShip.make(parcel, 900));
console.log(ecoFreight.make(parcel, 770));
console.log(sameDay.make(parcel, 1500));
QuickShip | To: Maya, Oak Ave | QS-0042 | $9.00
EcoFreight | To: Maya, Oak Ave | ECO42 | $7.70
SameDay | To: Maya, Oak Ave | SD/42 | $15.00
class Package {
  id: number;
  recipient: string;
  street: string;

  constructor(id: number, recipient: string, street: string) {
    this.id = id;
    this.recipient = recipient;
    this.street = street;
  }
}

class Label {
  carrier: string;
  barcode: (parcel: Package) => string;

  constructor(carrier: string, barcode: (parcel: Package) => string) {
    this.carrier = carrier;
    this.barcode = barcode;
  }

  // The routine, written once; the barcode step is the function this label was handed.
  make(parcel: Package, cents: number): string {
    const address = `To: ${parcel.recipient}, ${parcel.street}`;
    const rate = `${Math.floor(cents / 100)}.${String(cents % 100).padStart(2, "0")}`;
    return `${this.carrier} | ${address} | ${this.barcode(parcel)} | ${rate}`;
  }
}

const parcel = new Package(42, "Maya", "Oak Ave");
const quickShip = new Label("QuickShip", (p) => `QS-${String(p.id).padStart(4, "0")}`);
const ecoFreight = new Label("EcoFreight", (p) => `ECO${p.id}`);
const sameDay = new Label("SameDay", (p) => `SD/${p.id}`);
console.log(quickShip.make(parcel, 900));
console.log(ecoFreight.make(parcel, 770));
console.log(sameDay.make(parcel, 1500));
QuickShip | To: Maya, Oak Ave | QS-0042 | $9.00
EcoFreight | To: Maya, Oak Ave | ECO42 | $7.70
SameDay | To: Maya, Oak Ave | SD/42 | $15.00

Same three lines. If this shape looks familiar, it should: handing the varying part in is what the Strategy pattern does. The routine-with-a-gap is the same idea; what changed is how the gap is filled, by a subclass or by something handed in. Which one to pick is the next lesson.

Where you've already used it

  • Test frameworks: MSTest, JUnit, pytest and Node's test runner run the same routine for every test (set up, run the test, clean up), and you fill in the test and, when you need them, the set-up and clean-up steps.
  • A web framework's base controller or page class, whose methods you override to fill in your page's own steps while the framework runs the rest in its order.
  • Java's AbstractList: write get and size, and it supplies contains, indexOf and iteration, all built on your two steps.

When not to use it

  • When more than one step varies, independently. Two barcodes and two address formats would need four subclasses, one per combination; handing in two parts needs none.
  • When the step has to change while the program runs, such as a label printer that switches barcode formats mid-day. A subclass is fixed when the object is made.
  • When there's only one carrier. A routine with a gap and one filler is a routine.

The cost: inheritance ties each subclass to its base class, so a change to the routine reaches every subclass, and a reader has to look in two classes to see one label.

Look-alike: Strategy fills the same gap with an object or function handed in; Strategy or Template Method? compares them, and Factory Method, next, is a template method whose step makes an object.

How often you'll meet it: now and then in your own code; every day inside frameworks (our estimate).

Check yourself

2 questions to try on the lesson page.

So what

When sibling classes copy the same routine and differ in one step, give the routine a home in a base class and leave one gap. A fix to the shared steps is made once, and each carrier fills in only what's really its own.

Key terms

Cheat sheets