Deep Dive
low level designdesign patternsoop

Template Method: Freeze the Recipe, Swap the Ingredients

When CSV, JSON, and XML importers all do the same four steps in the same order but differ in two of them, three near-identical pipelines is the smell. Template Method puts the order in one place and lets subclasses fill only the steps that vary.

·15 min read
Easy

Your ingestion service imports customer catalogs. It started with CSV: parse the rows, validate them, transform to your internal schema, save to the warehouse. Clean, four steps, one class.

Then a partner sent JSON, so someone copied CsvImporter into JsonImporter and changed the parse step. Then XML. Three classes now, and each one carries its own copy of the validate → save logic and its own copy of the ordering. Last week the warehouse got a new required column, so validation had to change — in three files. One of them was missed. XML imports have been quietly skipping the check for eleven days.

The three importers aren’t really three algorithms. They’re one algorithm — parse, validate, transform, save, in that order — that differs in exactly two steps. Copy-paste spread the invariant part across all three and let it rot independently. The Gang of Four named the fix.

The intuition: a recipe fixes the steps, not the ingredients

A recipe for a cake tells you the order: cream the butter and sugar, fold in the dry ingredients, pour into a tin, bake, cool. That skeleton never changes. What varies between a vanilla cake and a chocolate one is a couple of ingredients slotted into fixed steps — you don’t reorder “bake” and “cool” to make it chocolate.

Template Method is that recipe. The base class writes down the steps and their order once. Each subclass supplies only the ingredients that differ — the parse step for CSV vs JSON — and inherits the rest of the recipe untouched. Nobody gets to rearrange the baking.

The members-only walkthrough picks up from here: the UML skeleton and a walk through the base class, the annotated Java and Python code with two concrete processors, a live class box, the anti-pattern of overriding the skeleton, how Template Method squares off against Strategy, where it hides in AbstractList, HttpServlet, and JdbcTemplate, the fragile-base-class trap, and an interview corner with a coding challenge and a quiz.

Members only

Keep reading with Premium

You've reached the members-only part of this deep-dive — the full implementation, the interactive ring simulator, and the step-by-step walkthrough. Unlock it with a membership.

Related Articles