7
Back to Boss Battles

Template MethodVSStrategy

The Problem

Scenario A β€” Template Method territory: You build report generators for PDF, CSV, and Excel. The flow is always: fetch data β†’ validate β†’ transform β†’ render output. Only the render step differs. You want to enforce this skeleton so no report skips validation.

Scenario B β€” Strategy territory: Your export service can format data as JSON, XML, or YAML. The caller picks the format at runtime. There's no fixed skeleton β€” just a format operation that varies.


Why They Look Alike

Both solve "parts of an algorithm vary." Both use polymorphism so different implementations handle the varying part. Both let you add new variants without changing the core logic.

Rendering diagram…

The Core Difference

AspectTemplate MethodStrategy
MechanismInheritance β€” subclass overrides stepsComposition β€” inject a strategy object
What variesIndividual steps within a fixed skeletonThe entire algorithm
ControlParent class controls the flowClient controls which strategy
Adding variantsCreate a new subclassCreate a new strategy class
Runtime swapNo β€” fixed at instantiationYes β€” swap strategy anytime
CouplingSubclass is tightly coupled to parentStrategy is loosely coupled to context
InversionHollywood Principle ("don't call us, we call you")Delegation ("you do this part")

One sentence: Template Method fixes the skeleton and lets subclasses fill in steps; Strategy lets you swap the whole algorithm via composition.


Side-by-Side Code

Template Method β€” Report generator skeleton

typescript
1abstract class ReportGenerator {
2 // Template method β€” the skeleton is fixed
3 async generate(): Promise<Buffer> {
4 const rawData = await this.fetchData();
5 this.validate(rawData);
6 const transformed = this.transform(rawData);
7 return this.render(transformed); // only this varies
8 }
9
10 protected abstract fetchData(): Promise<unknown[]>;
11 protected abstract render(data: unknown[]): Buffer;
12
13 // Shared steps β€” not overridable
14 private validate(data: unknown[]): void {
15 if (data.length === 0) throw new Error('No data for report');
16 }
17
18 private transform(data: unknown[]): unknown[] {
19 return data.map((row) => ({ ...row as object, generatedAt: new Date() }));
20 }
21}
22
23class PDFReportGenerator extends ReportGenerator {
24 protected async fetchData(): Promise<unknown[]> {
25 return this.db.query('SELECT * FROM orders');
26 }
27
28 protected render(data: unknown[]): Buffer {
29 return this.pdfLib.create(data);
30 }
31}

Strategy β€” Interchangeable formatter

typescript
1interface Formatter {
2 format(data: unknown[]): string;
3}
4
5class JsonFormatter implements Formatter {
6 format(data: unknown[]): string {
7 return JSON.stringify(data, null, 2);
8 }
9}
10
11class CsvFormatter implements Formatter {
12 format(data: unknown[]): string {
13 const headers = Object.keys(data[0] as object).join(',');
14 const rows = data.map((r) => Object.values(r as object).join(','));
15 return [headers, ...rows].join('\n');
16 }
17}
18
19class ExportService {
20 constructor(private formatter: Formatter) {}
21
22 export(data: unknown[]): string {
23 return this.formatter.format(data); // no skeleton, just delegate
24 }
25
26 setFormatter(formatter: Formatter): void {
27 this.formatter = formatter; // can swap at runtime
28 }
29}

Decision Rules

SignalChooseWhy
Fixed multi-step algorithm where only some steps varyTemplate MethodSkeleton enforces the process
Entire behavior varies, no shared skeletonStrategyNothing to template
Need to swap behavior at runtimeStrategyComposition allows runtime changes
Need to enforce that certain steps always run (validation, logging)Template MethodParent controls the flow
Favor composition over inheritanceStrategyAvoids subclass explosion
NestJS lifecycle hooks, test setUp/tearDownTemplate MethodFramework controls the skeleton
Pluggable algorithms (sort, format, pricing)StrategyJust swap the strategy

The Trick Question

"Your ETL pipeline has stages: extract, transform, load. Different data sources need different extract logic, and different targets need different load logic. Which pattern?"

This looks like Template Method (fixed skeleton with variable steps), and it often IS. But if you need to mix and match extractors and loaders independently (MySQL extract + S3 load, or API extract + Postgres load), that's Strategy β€” inject an ExtractStrategy and a LoadStrategy. Template Method ties them into one class hierarchy.

The tell: if extract and load vary independently, use Strategy (two injected strategies). If they always vary together as a unit, Template Method works.


Interview Angles

Q: Can you combine both patterns? Yes. A Template Method can use a Strategy for one of its variable steps. The skeleton is fixed by the base class, but one step delegates to an injected strategy. This avoids deep inheritance while keeping the skeleton.

Q: Which is more testable? Strategy β€” you can test the context with a mock strategy, and test each strategy in isolation. Template Method requires subclassing to test, which couples tests to the base class.

Q: How does NestJS relate to Template Method? NestJS module lifecycle (onModuleInit, onModuleDestroy) is Template Method. The framework controls the skeleton (startup sequence). You override specific hooks. Guards and interceptors are more like Strategy/Decorator.

Q: When does Template Method become an anti-pattern? When the inheritance hierarchy grows deep (3+ levels) or when you need to vary multiple steps independently. At that point, refactor to Strategy β€” inject the varying parts instead of subclassing for every combination.