Polski

Article · Template Method

Template Method: a fixed recipe, interchangeable ingredients

The Template Method pattern through importing supplier price lists: the base class fixes the order of steps, and subclasses provide parsing and optional hooks. The Hollywood principle, an inheritance-free variant in Go and code in five languages.

By · · 13 min read

Every kind of Halina's pierogi follows the same recipe: dough, filling, folding, boiling, sometimes frying afterwards. The filling changes; the order never does. Template Method writes such a recipe down in a base class and leaves subclasses only the steps that really differ. In the pierogi place's code, that recipe is importing price lists from suppliers.

1
method fixes the order – run() – shared by all imports
1
required step – parse() – every supplier has a different format
1
optional hook – adjust() – e.g. a cooling fee

The problem: two imports, one logic, two copies

The farm sends prices as CSV, the dairy as JSON. The first versions of the imports were written by copy and tweak:

imports_before.py
def import_farm_csv(raw: str) -> int:
    items = [line.split(";") for line in raw.splitlines() if line]
    valid = [i for i in items if i[0] and float(i[2].replace(",", ".")) > 0]
    db.save_prices(valid)
    return len(valid)


def import_dairy_json(raw: str) -> int:
    items = json.loads(raw)
    valid = [i for i in items if i["name"]]  # someone forgot the price check here
    for i in valid:
        i["price"] = round(i["price"] * 1.02, 2)  # cooling fee
    db.save_prices(valid)
    return len(valid)

Both functions do the same thing: parse, validate, adjust and save. Only the first step and the dairy's fee differ. The copied validation has already drifted – in the dairy import someone lost the price check, so cheese for 0 PLN would end up in the database. A third supplier would mean a third copy and a third place to forget a rule.

The solution: a skeleton in the base class

The shared flow moves to the base class as the run() method. It calls the steps in order: parse() is abstract, so every subclass has to provide it; isValid() and save() are private and shared; adjust() is a hook – it has a default "change nothing" implementation, but a subclass may override it.

Diagram: Who calls whom: the Hollywood principle
Diagram: The structure of the Template Method pattern
ElementIn the exampleWho defines it
Template methodrun()the base class; not overridable (final, non-virtual)
Abstract stepparse()every subclass, mandatory
Hookadjust()the base class (default), a subclass optionally
Shared stepisValid(), save()the base class, privately

Implementation in five languages

C#, TypeScript, Java and Python implement the pattern classically – with an abstract class. In Java the template method is final; in C# it is simply not virtual. Go has no inheritance, so the skeleton is a function taking an interface with the required step, and the hook is detected with a type assertion: if the parser also implements Adjuster, the function uses it.

Template Method – price list import

PriceListImport.cs
using System.Globalization;
using System.Text.Json;

Console.WriteLine(new FarmCsvImport().Run("cheese;kg;24,50\npotatoes;kg;3,20\nonions;kg;-1"));
Console.WriteLine(new DairyJsonImport().Run("""[{"name":"cream","unit":"l","price":12.0}]"""));

public sealed record PriceItem(string Name, string Unit, decimal Price);
public sealed record ImportReport(int Imported, int Rejected);

public abstract class PriceListImport
{
    // The template method: a fixed sequence of steps, deliberately not virtual.
    public ImportReport Run(string raw)
    {
        var items = Parse(raw).ToList();
        var valid = items.Where(IsValid).Select(Adjust).ToList();
        Save(valid);
        return new ImportReport(valid.Count, items.Count - valid.Count);
    }

    protected abstract IEnumerable<PriceItem> Parse(string raw); // required step

    protected virtual PriceItem Adjust(PriceItem item) => item; // optional hook

    private static bool IsValid(PriceItem i) => i.Name.Length > 0 && i.Price > 0;

    private void Save(List<PriceItem> items) =>
        items.ForEach(i => Console.WriteLine($"{GetType().Name}: {i.Name} = {i.Price:0.00} PLN/{i.Unit}"));
}

public sealed class FarmCsvImport : PriceListImport
{
    protected override IEnumerable<PriceItem> Parse(string raw) =>
        raw.Split('\n', StringSplitOptions.RemoveEmptyEntries)
           .Select(line => line.Split(';'))
           .Select(c => new PriceItem(c[0], c[1], decimal.Parse(c[2].Replace(',', '.'), CultureInfo.InvariantCulture)));
}

public sealed class DairyJsonImport : PriceListImport
{
    private static readonly JsonSerializerOptions Options = new(JsonSerializerDefaults.Web);

    protected override IEnumerable<PriceItem> Parse(string raw) =>
        JsonSerializer.Deserialize<List<PriceItem>>(raw, Options) ?? [];

    // The dairy adds a 2% cooling fee to every price.
    protected override PriceItem Adjust(PriceItem item) => item with { Price = Math.Round(item.Price * 1.02m, 2) };
}
price-list-import.ts
type PriceItem = { name: string; unit: string; price: number };
type ImportReport = { imported: number; rejected: number };

abstract class PriceListImport {
  // The template method: subclasses fill in steps but never change their order.
  run(raw: string): ImportReport {
    const items = this.parse(raw);
    const valid = items.filter((i) => this.isValid(i)).map((i) => this.adjust(i));
    this.save(valid);
    return { imported: valid.length, rejected: items.length - valid.length };
  }

  protected abstract parse(raw: string): PriceItem[]; // required step

  protected adjust(item: PriceItem): PriceItem { return item; } // optional hook

  private isValid(i: PriceItem): boolean { return i.name.length > 0 && i.price > 0; }

  private save(items: PriceItem[]): void {
    for (const i of items) console.log(`${this.constructor.name}: ${i.name} = ${i.price.toFixed(2)} PLN/${i.unit}`);
  }
}

class FarmCsvImport extends PriceListImport {
  protected parse(raw: string): PriceItem[] {
    return raw.split('\n').filter(Boolean).map((line) => {
      const [name, unit, price] = line.split(';');
      return { name, unit, price: Number(price.replace(',', '.')) };
    });
  }
}

class DairyJsonImport extends PriceListImport {
  protected parse(raw: string): PriceItem[] {
    return JSON.parse(raw) as PriceItem[];
  }

  // The dairy adds a 2% cooling fee to every price.
  protected override adjust(item: PriceItem): PriceItem {
    return { ...item, price: Math.round(item.price * 102) / 100 };
  }
}

console.log(new FarmCsvImport().run('cheese;kg;24,50\npotatoes;kg;3,20\nonions;kg;-1')); // imported 2, rejected 1
console.log(new DairyJsonImport().run('[{"name":"cream","unit":"l","price":12}]'));      // cream = 12.24
PriceListImport.java
import java.util.Arrays;
import java.util.List;
import java.util.regex.Pattern;

record PriceItem(String name, String unit, double price) {}
record ImportReport(int imported, int rejected) {}

public abstract class PriceListImport {
    // The template method: final, so subclasses cannot change the order of steps.
    public final ImportReport run(String raw) {
        List<PriceItem> items = parse(raw);
        List<PriceItem> valid = items.stream().filter(this::isValid).map(this::adjust).toList();
        save(valid);
        return new ImportReport(valid.size(), items.size() - valid.size());
    }

    protected abstract List<PriceItem> parse(String raw); // required step

    protected PriceItem adjust(PriceItem item) { return item; } // optional hook

    private boolean isValid(PriceItem i) { return !i.name().isBlank() && i.price() > 0; }

    private void save(List<PriceItem> items) {
        items.forEach(i -> System.out.printf("%s: %s = %.2f PLN/%s%n", getClass().getSimpleName(), i.name(), i.price(), i.unit()));
    }

    public static void main(String[] args) {
        System.out.println(new FarmCsvImport().run("cheese;kg;24,50\npotatoes;kg;3,20\nonions;kg;-1"));
        System.out.println(new DairyLineImport().run("cream|l|12.00"));
    }
}

class FarmCsvImport extends PriceListImport {
    @Override protected List<PriceItem> parse(String raw) {
        return raw.lines().filter(l -> !l.isBlank()).map(l -> l.split(";"))
            .map(c -> new PriceItem(c[0], c[1], Double.parseDouble(c[2].replace(',', '.')))).toList();
    }
}

class DairyLineImport extends PriceListImport {
    private static final Pattern SEP = Pattern.compile("\\|");

    @Override protected List<PriceItem> parse(String raw) {
        return raw.lines().map(SEP::split).map(c -> new PriceItem(c[0], c[1], Double.parseDouble(c[2]))).toList();
    }

    // The dairy adds a 2% cooling fee to every price.
    @Override protected PriceItem adjust(PriceItem i) {
        return new PriceItem(i.name(), i.unit(), Math.round(i.price() * 102) / 100.0);
    }
}
import.go
package main

import (
	"encoding/json"
	"fmt"
	"math"
	"strconv"
	"strings"
)

type PriceItem struct {
	Name  string  `json:"name"`
	Unit  string  `json:"unit"`
	Price float64 `json:"price"`
}

// Parser is the required step; Adjuster is an optional hook detected at runtime.
type Parser interface{ Parse(raw string) ([]PriceItem, error) }
type Adjuster interface{ Adjust(PriceItem) PriceItem }

// Run is the template: Go has no inheritance, so the skeleton is a function over an interface.
func Run(p Parser, raw string) (imported, rejected int, err error) {
	items, err := p.Parse(raw)
	if err != nil {
		return 0, 0, err
	}
	for _, it := range items {
		if it.Name == "" || it.Price <= 0 {
			rejected++
			continue
		}
		if a, ok := p.(Adjuster); ok {
			it = a.Adjust(it)
		}
		fmt.Printf("%T: %s = %.2f PLN/%s\n", p, it.Name, it.Price, it.Unit) // save
		imported++
	}
	return imported, rejected, nil
}

type FarmCSV struct{}

func (FarmCSV) Parse(raw string) ([]PriceItem, error) {
	var out []PriceItem
	for _, line := range strings.Fields(raw) {
		c := strings.Split(line, ";")
		price, err := strconv.ParseFloat(strings.Replace(c[2], ",", ".", 1), 64)
		if err != nil {
			return nil, err
		}
		out = append(out, PriceItem{c[0], c[1], price})
	}
	return out, nil
}

type DairyJSON struct{}

func (DairyJSON) Parse(raw string) (items []PriceItem, err error) {
	err = json.Unmarshal([]byte(raw), &items)
	return items, err
}

// Adjust adds the dairy's 2% cooling fee.
func (DairyJSON) Adjust(i PriceItem) PriceItem {
	i.Price = math.Round(i.Price*102) / 100
	return i
}

func main() {
	fmt.Println(Run(FarmCSV{}, "cheese;kg;24,50\npotatoes;kg;3,20\nonions;kg;-1"))
	fmt.Println(Run(DairyJSON{}, `[{"name":"cream","unit":"l","price":12}]`))
}
price_list_import.py
import json
from abc import ABC, abstractmethod
from dataclasses import dataclass, replace


@dataclass(frozen=True)
class PriceItem:
    name: str
    unit: str
    price: float


class PriceListImport(ABC):
    def run(self, raw: str) -> tuple[int, int]:
        """The template method: subclasses fill in steps, never the order."""
        items = self.parse(raw)
        valid = [self.adjust(i) for i in items if self._is_valid(i)]
        self._save(valid)
        return len(valid), len(items) - len(valid)

    @abstractmethod
    def parse(self, raw: str) -> list[PriceItem]:
        """Required step."""

    def adjust(self, item: PriceItem) -> PriceItem:
        """Optional hook – returns the item unchanged by default."""
        return item

    @staticmethod
    def _is_valid(item: PriceItem) -> bool:
        return bool(item.name) and item.price > 0

    def _save(self, items: list[PriceItem]) -> None:
        for i in items:
            print(f"{type(self).__name__}: {i.name} = {i.price:.2f} PLN/{i.unit}")


class FarmCsvImport(PriceListImport):
    def parse(self, raw: str) -> list[PriceItem]:
        rows = (line.split(";") for line in raw.splitlines() if line)
        return [PriceItem(name, unit, float(price.replace(",", "."))) for name, unit, price in rows]


class DairyJsonImport(PriceListImport):
    def parse(self, raw: str) -> list[PriceItem]:
        return [PriceItem(**row) for row in json.loads(raw)]

    def adjust(self, item: PriceItem) -> PriceItem:
        return replace(item, price=round(item.price * 1.02, 2))  # 2% cooling fee


print(FarmCsvImport().run("cheese;kg;24,50\npotatoes;kg;3,20\nonions;kg;-1"))  # (2, 1)
print(DairyJsonImport().run('[{"name": "cream", "unit": "l", "price": 12.0}]'))  # (1, 0)

The rest of this article is for members

Create a free account or sign in to read it all. Still ahead:

  • A template without inheritance
  • Step by step
  • Template Method vs Strategy
  • When to use it and when not to
  • Related patterns
  • In practice
  • Test yourself

Create a free account · Sign in