Patterncore
Template Method pattern
Also called Template Method, hook method, non-virtual interface.
A base class method fixes the steps of an algorithm and calls other methods for the steps that vary. Subclasses override those steps and leave the order of the steps alone.
- Family
- behavioral-design
- Intent
- Define the skeleton of an algorithm in one operation, and let subclasses redefine some of its steps without changing the structure of the algorithm.
- Refactorings
- Form template method
Intent
Define the skeleton of an algorithm in an operation, and defer some steps to subclasses. Subclasses then redefine those steps without changing the structure of the algorithm.1 The base class owns the order. The subclasses own the details.
Problem
A program loads records from text in two formats. One is CSV, with lines such as pen,3. The other is key and value, with lines such as pen=3. Both loaders must strip each line, skip blank lines and comments, parse the rest, and filter the result. Only the parse step, and in one case the filter, differ.
The first version has two loaders, each with its own loop. The loops are copies, and copies drift apart. A fix in one is missed in the other. Here, the key and value loader does not skip comments, and a comment becomes a record:
This code runs but gives a wrong answer on purpose.
def load_csv(lines):
records = []
for line in lines:
line = line.strip()
if not line or line.startswith("#"):
continue
name, count = line.split(",")
records.append((name, int(count)))
return records
def load_key_value(lines):
records = []
for line in lines:
line = line.strip()
if not line: # the copy lacks the comment check
continue
name, _, count = line.partition("=")
if int(count) > 0:
records.append((name, int(count)))
return records
print(load_csv(["# stock", "pen,3", "book,1"]))
print(load_key_value(["pen=3", "#cup=5"]))
[('pen', 3), ('book', 1)]
[('pen', 3), ('#cup', 5)]
Design Patterns uses an application framework. The base class opens a document in fixed steps: check that it can be opened, make the document object, add it to the application, and read it. Each kind of application changes some of those steps.1 The forces are these. Several classes share an algorithm and differ in a few steps. The shared part must exist once. And the order of the steps must not change from one class to the next.
Solution
Design Patterns names two participants.1
- AbstractClass defines the template method, which calls the steps in order. It declares the steps that vary as primitive operations.
- ConcreteClass implements the primitive operations for one case.
The base class calls the subclass, not the other way round. Design Patterns calls this inverted control structure the Hollywood principle.1 The subclass gives the steps and does not call the template.
The steps come in two kinds. A primitive operation, often abstract, has no default, and each subclass must give it. In the loader, parse is one. A hook has a default, often one that does nothing, and a subclass may override it. In the loader, accept is a hook whose default keeps every record. Design Patterns asks the author of the base class to say which steps are hooks and which must be overridden, since a subclass author cannot tell otherwise.1
The template method itself should not be overridden. Languages state this in different ways:
| Language | How the template is kept fixed | How the steps are marked |
|---|---|---|
| Java | final on the template method5 |
protected abstract and protected methods |
| C# | methods are not virtual unless marked, so the template is fixed by default6 | abstract and virtual |
| Kotlin | members are final unless marked open7 |
abstract and open |
| C++ | a public non-virtual function4 | private virtual functions |
| Python | typing.final, checked by type checkers only819 |
abc.abstractmethod for the primitive operations9 |
| Rust | no way; a provided trait method can be replaced10 | required methods and provided methods |
| TypeScript, JavaScript | no way | abstract in TypeScript; a method that throws in JavaScript |
| Go | the template is a function, which cannot be overridden | an interface, and an optional interface for a hook |
In C++, Sutter's guidelines turn the pattern into a rule of class design. Prefer to make interfaces non-virtual, using Template Method. Prefer to make virtual functions private. Make a virtual function protected only if derived classes need to call the base version.4 In a note added to the article, Sutter names this the Non-Virtual Interface idiom, or NVI. He describes it as a more restricted idiom with a form similar to Template Method.4 The C++ example file follows it.
Example
The example files load the CSV lines # stock, pen,3, an empty line and book,1, and the key and value lines pen=3, # sold out and cup=0. The key and value loader overrides the hook to drop records with a count of zero. Each file prints csv: pen:3 book:1 and kv: pen:3:
| Language | Form |
|---|---|
| Python | an abstract base class, with @final on the template8 |
| JavaScript | a base class whose parse throws until a subclass overrides it |
| TypeScript | an abstract class with protected steps |
| Java | a final template, a protected abstract step and a protected hook5 |
| C# | a non-virtual template, an abstract step and a virtual hook6 |
| C++ | the non-virtual interface idiom with private virtual steps4 |
| Go | a function that takes an interface, and an optional interface for the hook12 |
| Rust | a trait whose provided method calls its required method10 |
from abc import ABC, abstractmethod
from typing import final
class Loader(ABC):
@final
def load(self, lines: list[str]) -> list[tuple[str, int]]:
"""The template method: the fixed steps, in a fixed order."""
records = []
for line in lines:
line = line.strip()
if not line or line.startswith("#"):
continue
record = self.parse(line)
if self.accept(record):
records.append(record)
return records
@abstractmethod
def parse(self, line: str) -> tuple[str, int]:
"""A primitive operation: each subclass must give it."""
def accept(self, record: tuple[str, int]) -> bool:
"""A hook: subclasses may override it. The default keeps every record."""
return True
class CsvLoader(Loader):
def parse(self, line):
name, count = line.split(",")
return name, int(count)
class KeyValueLoader(Loader):
def parse(self, line):
name, _, count = line.partition("=")
return name, int(count)
def accept(self, record):
return record[1] > 0
def show(label, records):
print(f"{label}: " + " ".join(f"{name}:{count}" for name, count in records))
show("csv", CsvLoader().load(["# stock", "pen,3", "", "book,1"]))
show("kv", KeyValueLoader().load(["pen=3", "# sold out", "cup=0"]))
csv: pen:3 book:1
kv: pen:3
- Verdict: idiom. An abstract base class holds the template method
load.parseis abstract, so a subclass without it cannot be created.acceptis a hook with a default. typing.finalmarksloadas a method that subclasses must not override. Python does not enforce it when the program runs. A type checker reports an override.- The leading underscore convention, as in
_parse, is the usual way to say that a step is for subclasses and not for clients. Python has noprotected.
#include <iostream>
#include <string>
#include <utility>
#include <vector>
using Item = std::pair<std::string, int>;
class Loader {
public:
virtual ~Loader() = default;
// The public interface is non-virtual. It fixes the steps.
std::vector<Item> load(const std::vector<std::string>& lines) const {
std::vector<Item> records;
for (const auto& line : lines) {
if (line.empty() || line.front() == '#') continue;
Item record = parse(line);
if (accept(record)) records.push_back(std::move(record));
}
return records;
}
private:
// The steps are private and virtual. Derived classes override them but cannot call them.
virtual Item parse(const std::string& line) const = 0;
virtual bool accept(const Item&) const { return true; }
};
Item split(const std::string& line, char sep) {
auto at = line.find(sep);
return {line.substr(0, at), std::stoi(line.substr(at + 1))};
}
class CsvLoader final : public Loader {
Item parse(const std::string& line) const override { return split(line, ','); }
};
class KeyValueLoader final : public Loader {
Item parse(const std::string& line) const override { return split(line, '='); }
bool accept(const Item& record) const override { return record.second > 0; }
};
void show(const char* label, const std::vector<Item>& records) {
std::cout << label << ":";
for (const auto& [name, count] : records) std::cout << ' ' << name << ':' << count;
std::cout << '\n';
}
int main() {
show("csv", CsvLoader{}.load({"# stock", "pen,3", "", "book,1"}));
show("kv", KeyValueLoader{}.load({"pen=3", "# sold out", "cup=0"}));
}
csv: pen:3 book:1
kv: pen:3
- Verdict: idiom. The non-virtual interface idiom.
loadis public and non-virtual, and the steps are private and virtual. Herb Sutter recommends this form for C++ class design, and calls it NVI. - A derived class can override a private virtual function, but it cannot call the base version. The base class keeps control of when each step runs.
- The destructor is public and virtual, because client code may delete a derived loader through a
Loaderpointer. - The lines here have no surrounding spaces, so
loaddoes not trim them. The other examples trim each line.
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
public class Main {
record Item(String name, int count) {
@Override
public String toString() {
return name + ":" + count;
}
}
abstract static class Loader {
// The template method. final stops a subclass from changing the steps.
public final List<Item> load(List<String> lines) {
List<Item> records = new ArrayList<>();
for (String raw : lines) {
String line = raw.strip();
if (line.isEmpty() || line.startsWith("#")) {
continue;
}
Item record = parse(line);
if (accept(record)) {
records.add(record);
}
}
return records;
}
protected abstract Item parse(String line);
protected boolean accept(Item record) {
return true;
}
}
static final class CsvLoader extends Loader {
@Override
protected Item parse(String line) {
String[] parts = line.split(",");
return new Item(parts[0], Integer.parseInt(parts[1]));
}
}
static final class KeyValueLoader extends Loader {
@Override
protected Item parse(String line) {
String[] parts = line.split("=");
return new Item(parts[0], Integer.parseInt(parts[1]));
}
@Override
protected boolean accept(Item record) {
return record.count() > 0;
}
}
static void show(String label, List<Item> records) {
System.out.println(label + ": " + records.stream().map(Item::toString).collect(Collectors.joining(" ")));
}
public static void main(String[] args) {
show("csv", new CsvLoader().load(List.of("# stock", "pen,3", "", "book,1")));
show("kv", new KeyValueLoader().load(List.of("pen=3", "# sold out", "cup=0")));
}
}
csv: pen:3 book:1
kv: pen:3
- Verdict: idiom. The template method is
public final, the primitive operation isprotected abstract, and the hook isprotectedwith a default. Each modifier states one rule of the pattern, and the compiler enforces it. - Java methods can be overridden unless they are
final. A template method that is notfinalcan be replaced by a subclass, which breaks the fixed order of steps. java.io.InputStreamandjava.util.AbstractListin the standard library have this form (see the node).
Show("csv", new CsvLoader().Load(["# stock", "pen,3", "", "book,1"]));
Show("kv", new KeyValueLoader().Load(["pen=3", "# sold out", "cup=0"]));
static void Show(string label, List<Item> records) =>
Console.WriteLine($"{label}: {string.Join(" ", records.Select(r => $"{r.Name}:{r.Count}"))}");
record Item(string Name, int Count);
abstract class Loader
{
// Not virtual, so a derived class cannot override it.
public List<Item> Load(IEnumerable<string> lines)
{
var records = new List<Item>();
foreach (var raw in lines)
{
var line = raw.Trim();
if (line.Length == 0 || line.StartsWith('#')) continue;
var record = Parse(line);
if (Accept(record)) records.Add(record);
}
return records;
}
protected abstract Item Parse(string line);
protected virtual bool Accept(Item record) => true;
}
sealed class CsvLoader : Loader
{
protected override Item Parse(string line)
{
var parts = line.Split(',');
return new Item(parts[0], int.Parse(parts[1]));
}
}
sealed class KeyValueLoader : Loader
{
protected override Item Parse(string line)
{
var parts = line.Split('=');
return new Item(parts[0], int.Parse(parts[1]));
}
protected override bool Accept(Item record) => record.Count > 0;
}
csv: pen:3 book:1
kv: pen:3
- Verdict: idiom. C# methods are non-virtual unless they are marked
virtual,abstractoroverride.Loadhas none of these, so it is fixed.ParseisabstractandAcceptisvirtualwith a default. - A derived class that declares its own
Loadhides the base method and gets a compiler warning. A call through aLoaderreference still runs the baseLoad. - The defaults of the language match the pattern: a method must opt in to being a step that derived classes change.
class Loader {
// The template method. Subclasses are not meant to override it.
load(lines) {
const records = [];
for (const raw of lines) {
const line = raw.trim();
if (line === "" || line.startsWith("#")) continue;
const record = this.parse(line);
if (this.accept(record)) records.push(record);
}
return records;
}
parse(line) {
throw new Error(`${this.constructor.name} must implement parse`);
}
accept(record) {
return true; // the hook: keep every record unless a subclass says otherwise
}
}
class CsvLoader extends Loader {
parse(line) {
const [name, count] = line.split(",");
return [name, Number(count)];
}
}
class KeyValueLoader extends Loader {
parse(line) {
const [name, count] = line.split("=");
return [name, Number(count)];
}
accept([, count]) {
return count > 0;
}
}
const show = (label, records) => console.log(`${label}: ${records.map(([n, c]) => `${n}:${c}`).join(" ")}`);
show("csv", new CsvLoader().load(["# stock", "pen,3", "", "book,1"]));
show("kv", new KeyValueLoader().load(["pen=3", "# sold out", "cup=0"]));
csv: pen:3 book:1
kv: pen:3
- Verdict: idiom. A base class with
extends. JavaScript has no abstract methods, soparsethrows until a subclass gives it. The error appears on the first call, not when the object is made. - JavaScript has no
final. A subclass can overrideload, and nothing reports it. - The hook
accepttakes a destructured array, soKeyValueLoaderreads the count by position.
type Item = readonly [name: string, count: number];
abstract class Loader {
load(lines: readonly string[]): Item[] {
const records: Item[] = [];
for (const raw of lines) {
const line = raw.trim();
if (line === "" || line.startsWith("#")) continue;
const record = this.parse(line);
if (this.accept(record)) records.push(record);
}
return records;
}
protected abstract parse(line: string): Item;
protected accept(_record: Item): boolean {
return true;
}
}
class CsvLoader extends Loader {
protected parse(line: string): Item {
const [name, count] = line.split(",");
return [name, Number(count)];
}
}
class KeyValueLoader extends Loader {
protected parse(line: string): Item {
const [name, count] = line.split("=");
return [name, Number(count)];
}
protected override accept([, count]: Item): boolean {
return count > 0;
}
}
const show = (label: string, records: Item[]): void =>
console.log(`${label}: ${records.map(([n, c]) => `${n}:${c}`).join(" ")}`);
show("csv", new CsvLoader().load(["# stock", "pen,3", "", "book,1"]));
show("kv", new KeyValueLoader().load(["pen=3", "# sold out", "cup=0"]));
csv: pen:3 book:1
kv: pen:3
- Verdict: idiom. An
abstractclass with anabstractmethod. The compiler rejectsnew Loader()and a subclass that does not implementparse. protectedkeepsparseandacceptout of the public interface. Clients callloadonly.- TypeScript has no
finalmodifier for methods, so a subclass can overrideload. Theoverridekeyword, withnoImplicitOverrideon, makes each override explicit, which helps a reader see one.
package main
import (
"fmt"
"strconv"
"strings"
)
type Item struct {
Name string
Count int
}
// Parser is the step that each format must give.
type Parser interface {
Parse(line string) Item
}
// Accepter is an optional hook. A parser that has no Accept method keeps every record.
type Accepter interface {
Accept(Item) bool
}
// Load is the template: a function, not a method of a base type.
func Load(p Parser, lines []string) []Item {
accept := func(Item) bool { return true }
if a, ok := p.(Accepter); ok {
accept = a.Accept
}
var records []Item
for _, raw := range lines {
line := strings.TrimSpace(raw)
if line == "" || strings.HasPrefix(line, "#") {
continue
}
if record := p.Parse(line); accept(record) {
records = append(records, record)
}
}
return records
}
func split(line, sep string) Item {
name, count, _ := strings.Cut(line, sep)
n, _ := strconv.Atoi(count)
return Item{name, n}
}
type CSV struct{}
func (CSV) Parse(line string) Item { return split(line, ",") }
type KeyValue struct{}
func (KeyValue) Parse(line string) Item { return split(line, "=") }
func (KeyValue) Accept(r Item) bool { return r.Count > 0 }
func show(label string, records []Item) {
parts := make([]string, len(records))
for i, r := range records {
parts[i] = fmt.Sprintf("%s:%d", r.Name, r.Count)
}
fmt.Printf("%s: %s\n", label, strings.Join(parts, " "))
}
func main() {
show("csv", Load(CSV{}, []string{"# stock", "pen,3", "", "book,1"}))
show("kv", Load(KeyValue{}, []string{"pen=3", "# sold out", "cup=0"}))
}
csv: pen:3 book:1
kv: pen:3
- Verdict: idiom. Go has no inheritance, so the template is a function that takes an interface. The steps are the interface's methods. This is the form of
sort.Sort, which runs a sort algorithm over theLen,LessandSwapmethods of its argument. - The hook is a second, optional interface.
Loadchecks for it with a type assertion and uses a default when it is absent. - A function cannot be overridden, so the order of the steps is fixed, as with a
finalmethod in Java.
#[derive(Debug)]
struct Item(String, u32);
trait Loader {
// A required method: each implementation must give it.
fn parse(&self, line: &str) -> Item;
// A hook: a default implementation that an implementation may replace.
fn accept(&self, _record: &Item) -> bool {
true
}
// The template: a provided method that calls the others.
fn load(&self, lines: &[&str]) -> Vec<Item> {
lines
.iter()
.map(|line| line.trim())
.filter(|line| !line.is_empty() && !line.starts_with('#'))
.map(|line| self.parse(line))
.filter(|record| self.accept(record))
.collect()
}
}
fn split(line: &str, sep: char) -> Item {
let (name, count) = line.split_once(sep).expect("a separator");
Item(name.to_string(), count.parse().expect("a count"))
}
struct Csv;
struct KeyValue;
impl Loader for Csv {
fn parse(&self, line: &str) -> Item {
split(line, ',')
}
}
impl Loader for KeyValue {
fn parse(&self, line: &str) -> Item {
split(line, '=')
}
fn accept(&self, record: &Item) -> bool {
record.1 > 0
}
}
fn show(label: &str, records: &[Item]) {
let parts: Vec<String> = records.iter().map(|Item(name, count)| format!("{name}:{count}")).collect();
println!("{label}: {}", parts.join(" "));
}
fn main() {
show("csv", &Csv.load(&["# stock", "pen,3", "", "book,1"]));
show("kv", &KeyValue.load(&["pen=3", "# sold out", "cup=0"]));
}
csv: pen:3 book:1
kv: pen:3
- Verdict: native. A trait's provided methods are template methods. A default method can call the required methods of the same trait, even though the trait does not implement them.
Iteratorin the standard library is the main case: an implementation givesnext, andmap,filter,collectand dozens of other methods are defaults built on it. - Rust has no
finalfor trait methods. An implementation may replaceloadtoo. A free function generic overT: Loaderis the form that no implementation can replace. - There is no inheritance of state. The trait cannot hold fields, so data that the template needs must come through methods or arguments.
Consequences
Design Patterns calls template methods a fundamental technique for code reuse, and notes that they are important in class libraries, because they factor out the common behaviour.1 The loop of the loader exists once. A fix to the comment rule reaches every format. A new format is one class with one method.
The costs come from inheritance. The steps are bound when the subclass is written, so a loader cannot change its parse step while the program runs. Each combination of steps needs a class. A loader with two parse formats and two filters needs four subclasses, or a second mechanism. The subclass depends on the base class's protected interface, and a change to the order of the steps can break subclasses that relied on it.
Call super. A base class that asks subclasses to override a method and call the base version from it has a weak form of the pattern. Fowler calls this the call super smell. When a programmer must remember to make a call each time, the API is at fault. The fix is a template method that makes the call itself and then calls a hook.3 This subclass forgets the call, and the comment check is lost:
This code runs but gives a wrong answer on purpose.
class Loader:
def clean(self, line):
"""Subclasses that override this must call super().clean(line)."""
line = line.strip()
return None if not line or line.startswith("#") else line
def load(self, lines):
records = []
for line in lines:
line = self.clean(line)
if line is not None:
records.append(self.parse(line))
return records
class UpperCsvLoader(Loader):
def clean(self, line):
return line.strip().upper() # forgot super().clean(line)
def parse(self, line):
name, count = line.split(",")
return name, int(count)
print(UpperCsvLoader().load(["pen,3", "# note,0", "book,1"]))
[('PEN', 3), ('# NOTE', 0), ('BOOK', 1)]
The fix keeps the check in load and calls a hook, such as transform(line), that returns the line unchanged by default. The subclass then overrides the hook and cannot skip the check. The example files have this shape: the base class strips and filters, and parse sees only the lines that passed.
A template that a subclass replaces. If the template method can be overridden, a subclass can change the order of the steps and break the contract. In Java, final stops this at compile time:5
This code does not compile, on purpose.
import java.util.List;
public class Main {
abstract static class Loader {
public final List<String> load(List<String> lines) {
return lines.stream().map(this::parse).toList();
}
protected abstract String parse(String line);
}
static final class CsvLoader extends Loader {
@Override
public List<String> load(List<String> lines) { // error: load is final in Loader
return lines;
}
@Override
protected String parse(String line) {
return line;
}
}
public static void main(String[] args) {
System.out.println(new CsvLoader().load(List.of("pen,3")));
}
}
Do not call the steps from a constructor. A template method that runs in the base class constructor calls steps of a subclass that is not fully built. C++ and Java handle this in different ways, and both surprise. The Factory Method pattern page shows both cases, since a factory method is often a step of a template method.
When not to use it
Do not use inheritance when the steps vary on their own. If parse formats and filters combine freely, pass them as two values. Two subclasses for two cases become four for four combinations, and the count grows with each axis.
Do not use it when the step must change at run time, or when the caller chooses it. Pass a function or a strategy object.
Do not use it in a language where a function value does the job with less code, and the template has only one or two steps. The comparison with Strategy below shows the function form.
Do not make a deep hierarchy of templates that call templates. A reader must then follow each step up and down the class tree to see what runs.
Variants and related patterns
Template Method and Strategy
Both patterns let part of an algorithm vary. Design Patterns states the difference: template methods use inheritance to vary part of an algorithm, and strategies use delegation to vary the entire algorithm.1 Norvig lists both among the patterns that first-class functions make less complex.2 With functions, the steps of a template become parameters, and the template becomes a function:
def load(lines, parse, accept=lambda record: True):
records = []
for line in lines:
line = line.strip()
if not line or line.startswith("#"):
continue
record = parse(line)
if accept(record):
records.append(record)
return records
def csv(line):
name, count = line.split(",")
return name, int(count)
def key_value(line):
name, _, count = line.partition("=")
return name, int(count)
print(load(["# stock", "pen,3", "book,1"], csv))
print(load(["pen=3", "cup=0"], key_value, accept=lambda record: record[1] > 0))
print(load(["pen,3", "cup,0"], csv, accept=lambda record: record[1] > 0)) # a combination with no class
[('pen', 3), ('book', 1)]
[('pen', 3)]
[('pen', 3)]
The last call combines the CSV parser with the filter of the other format. The class form would need a third subclass for it. The table below compares the two forms:
| Aspect | Template Method | Steps as functions or strategies |
|---|---|---|
| binding time | when the subclass is written | when the caller passes the values; can change at run time |
| what varies | some steps; the structure is fixed | any step; a strategy can replace the whole algorithm |
| combinations of steps | one subclass for each | free, with no extra types |
| access to the base class's state | yes, through protected members | only what the template passes as arguments |
| defaults for steps | hook methods | default parameter values |
| a missing step | a compile error, or an error when the object is made | an error at the call |
Choose the class form when the steps share state with the template, or when a class must give several related steps together. Choose functions when the steps are independent and few. The Strategy pattern page covers the delegation side.
Iterator-style traits. In Rust, a trait with one required method and many provided methods is a set of template methods. Iterator is the main case. An implementation gives next, and the provided methods build on it.1011 Python's collections.abc classes do the same with mixin methods. A class that inherits from Sequence and gives __getitem__ and __len__ gets __contains__, __iter__, index and count.17 See Iterator.
Go's function templates. sort.Sort takes a value of the interface sort.Interface, with Len, Less and Swap. The sort algorithm is fixed in the function, and the value gives the steps.12
Factory Method. A factory method is often a step of a template method. The template calls it to get an object that it then uses.1 See Factory Method pattern.
Refactoring. Kerievsky's refactoring Form Template Method starts from two methods in sibling subclasses that do similar steps in the same order. It moves the shared order into a template in the base class, and leaves the differing steps in the subclasses.18
Known uses
- CPython: BaseRequestHandler.init in socketserver.py at v3.14.0 calls
setup(), thenhandle()in atryblock, thenfinish()in afinallyblock. All three are hooks with empty defaults, and a handler class overrideshandle.1314 - OpenJDK:
java.io.InputStreamdeclaresread()as abstract. read(byte[], int, int) at jdk-25+36 callsread()in a loop, so a subclass that gives the one-byte read gets the bulk read. The documentation encourages subclasses to give a more efficient bulk read.15 - OpenJDK: AbstractList at jdk-25+36 documents that an unmodifiable list needs only
get(int)andsize(). Iteration, search and the other methods are built on those two.16 - Rust:
std::iter::Iteratorhas one required method,next, and the rest are provided.11
References
- Gamma, Helm, Johnson and Vlissides, Design Patterns, Elements of Reusable Object-Oriented Software, Addison-Wesley, 1994, Chapter 5, Template Method (Intent, Motivation, Participants, Collaborations, Consequences, Implementation, Related Patterns)
- Peter Norvig, Design Patterns in Dynamic Programming, Object World, May 1996, slide 10 (first-class functions make Command, Strategy, Template-Method and Visitor simpler)
- Martin Fowler, CallSuper, bliki, August 11, 2005, the whole entry (call super as a minor smell; the template method with a hook as the fix)
- Herb Sutter, Virtuality, C/C++ Users Journal 19(9), September 2001, Guidelines 1 to 4 (non-virtual interfaces; private virtual functions; protected only when derived classes call the base; the destructor)
- The Java Language Specification, Java SE 25 Edition, 8.4.3.3 final Methods
- C# language specification, Classes, 15.6.4 Virtual methods
- Kotlin documentation, Inheritance, Overriding methods
- The Python Standard Library, typing, Python 3.14, typing.final
- The Python Standard Library, abc, Python 3.14, abc.abstractmethod
- The Rust Programming Language, chapter 10.2, Default Implementations
- Rust standard library, std::iter, Implementing Iterator
- Go standard library, sort, func Sort; type Interface
- The Python Standard Library, socketserver, Python 3.14, BaseRequestHandler.setup, handle and finish
- CPython v3.14.0 source, Lib/socketserver.py, BaseRequestHandler.__init__, setup, handle and finish, lines 760 to 777
- OpenJDK jdk-25+36 source, java/io/InputStream.java, abstract read() at line 182; read(byte[], int, int), lines 283 to 308
- OpenJDK jdk-25+36 source, java/util/AbstractList.java, class documentation, lines 30 to 45
- The Python Standard Library, collections.abc, Python 3.14, Collections Abstract Base Classes (the table of abstract methods and mixin methods)
- Joshua Kerievsky, Refactoring to Patterns, Addison-Wesley, 2004, Chapter 8, Generalization, Form Template Method
- PEP 591, Adding a final qualifier to typing, The final decorator
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Visual | V0 none |
|
| Writing | W4 complete |
|
Tag RVYZ8D Edit this page History Report an error Markdown