skipnothing/Design Patterns

Template Method

Two export() methods sit in two classes: both open a file, write a header, write each row, and close. The only lines that differ are how a row gets formatted, yet you copied the whole skeleton.

  • ▸Two export() methods identical except for three lines mean you copied the whole shape to vary the formatting.
  • ▸Write the shape once in a parent and a new format becomes a subclass, not a fourth copy of it.
  • ▸The parent fixes the step order and can lock it; you write the steps, but never call the parent back.
BUILDS ON
01

Two Methods, One Shape

Open two files in the same project. CsvExporter.export(rows) opens a stream, writes a header line, loops the rows writing each one, writes a footer with the row count, and closes the stream. JsonExporter.export(rows) does the same five things in the same order: open, header, per-row, footer, close. Set them side by side and most lines match character for character. Only three differ: the header is id,name,total versus [, a row is r.id + ',' + r.name versus a JSON object, the footer is a blank line versus ].

You wrote the second exporter by copying the first and changing three lines. Now a bug turns up in the close logic, you forgot to flush before closing, and it lives in both files because you copied it into both. The open-write-close sequence, the part that was never the interesting part, got duplicated wholesale so you could vary the three lines that actually differ. Add a third format and you copy the sequence a third time. The shape is identical; the variation is tiny; the duplication is total.

SPOT THE THREE LINES THAT DIFFER

Keep going, sign up to unlock the rest

4 more parts in this topic, plus 18+ more topics in Design Patterns.

Sign up, it's freeSee the full Design Patterns