Form Template Method
Two methods in subclasses perform similar steps in the same order.
“Two methods in subclasses perform similar steps in the same order, yet the steps are different.”
Standardize the skeleton.
graph LR
A[Subclass A: Steps 1, 2a, 3] -->|Refactoring| C[Superclass: Steps 1, abstract 2, 3]
B[Subclass B: Steps 1, 2b, 3] --> C
When to apply (Smells)
- Duplication: Similar methods in siblings.
Motivation
- DRY: Define the invariant parts once.
Mechanics (Steps)
- Extract the steps into separate methods (same signature).
- Pull up the “template method” that calls these steps.
- Each subclass implements the specific steps.
Explanation
Problem
Site A requires login, page load, then logout. Site B requires login, app load, then logout.
Solution
Parent Site: run() { login(); load(); logout(); }
Subclasses implement load().
Pros and Cons
| Pros | Cons |
|---|---|
Code example
Typescript
Before
After
PHP
Before
After