Removing duplication with Template Method
45 min · Advanced
Need help? Ask a tutor on WhatsApp (opens in a new tab)ShopLite prints a CSV sales report and a text sales report that run the same steps. When the paid-orders filter changes, someone fixes one report and forgets the other, and the two disagree.
Smell: two classes with near-identical steps
A duplicated step sequence is two or more methods that run the same steps in the same order and differ only in a few lines, such as the header text or the row format.
ShopLite prints a CSV report and a text report. Both filter paid orders, sort, print a header, loop over rows and add a total. Only the header and the row format differ.
Example 1 · Two reports with the same steps
import java.util.ArrayList;import java.util.Comparator;import java.util.List;
record Order(String id, String customer, String status, int total) { }
class CsvOrderReport { void print(List<Order> orders) { List<Order> paid = new ArrayList<>(); for (Order o : orders) { if (o.status().equals("PAID")) paid.add(o); } paid.sort(Comparator.comparing(Order::id)); System.out.println("id,customer,total"); int sum = 0; for (Order o : paid) { System.out.println(o.id() + "," + o.customer() + "," + o.total()); sum += o.total(); } System.out.println("TOTAL,," + sum); }}
class TextOrderReport { void print(List<Order> orders) { List<Order> paid = new ArrayList<>(); for (Order o : orders) { if (o.status().equals("PAID")) paid.add(o); } paid.sort(Comparator.comparing(Order::id)); System.out.println("Paid orders"); int sum = 0; for (Order o : paid) { System.out.println(" " + o.id() + " " + o.customer() + " Rs. " + o.total()); sum += o.total(); } System.out.println("Total: Rs. " + sum); }}
public class DuplicatedReportsDemo { public static void main(String[] args) { List<Order> orders = List.of( new Order("ORD-3", "Kabir", "PAID", 1499), new Order("ORD-1", "Riya", "PAID", 899), new Order("ORD-2", "Meera", "CANCELLED", 60)); new CsvOrderReport().print(orders); new TextOrderReport().print(orders); }}id,customer,total ORD-1,Riya,899 ORD-3,Kabir,1499 TOTAL,,2398 Paid orders ORD-1 Riya Rs. 899 ORD-3 Kabir Rs. 1499 Total: Rs. 2398
What this code does
- Both
printmethods filter paid orders, sort by id, print a header, loop and total. Only the header, row and total lines differ. - Any change to the shared steps, such as including delivered orders, has to be made twice.
The cost shows up later. If paid orders must now also include DELIVERED ones, someone fixes the filter in the CSV report and forgets the text report. The two reports then disagree, and nobody notices until a customer does.
Predict the output
Fix one copy, forget the other
The filter was fixed in the CSV report only.
One order has the status DELIVERED. What do the two reports show?
Extracting the common skeleton into a base class
A template method is a method in an abstract base class that runs the fixed steps in order and calls separate methods for the parts that differ. Subclasses fill in those parts but cannot change the order.
Copy one report into an abstract base class, then replace each line that differs with a call to a new method such as header() or row(o). The final method below runs the steps.
Example 2 · The skeleton moved into a base class
import java.util.ArrayList;import java.util.Comparator;import java.util.List;
record Order(String id, String customer, String status, int total) { }
abstract class OrderReport { // The template method: the fixed order of steps. final, so subclasses cannot reorder them. final void print(List<Order> orders) { List<Order> paid = new ArrayList<>(); for (Order o : orders) { if (o.status().equals("PAID")) paid.add(o); } paid.sort(Comparator.comparing(Order::id)); System.out.println(header()); int sum = 0; for (Order o : paid) { System.out.println(row(o)); sum += o.total(); } System.out.println(totalLine(sum)); }
abstract String header(); abstract String row(Order o); abstract String totalLine(int sum);}
class CsvOrderReport extends OrderReport { String header() { return "id,customer,total"; } String row(Order o) { return o.id() + "," + o.customer() + "," + o.total(); } String totalLine(int sum) { return "TOTAL,," + sum; }}
class TextOrderReport extends OrderReport { String header() { return "Paid orders"; } String row(Order o) { return " " + o.id() + " " + o.customer() + " Rs. " + o.total(); } String totalLine(int sum) { return "Total: Rs. " + sum; }}
public class TemplateReportsDemo { public static void main(String[] args) { List<Order> orders = List.of( new Order("ORD-3", "Kabir", "PAID", 1499), new Order("ORD-1", "Riya", "PAID", 899), new Order("ORD-2", "Meera", "CANCELLED", 60)); new CsvOrderReport().print(orders); new TextOrderReport().print(orders); }}id,customer,total ORD-1,Riya,899 ORD-3,Kabir,1499 TOTAL,,2398 Paid orders ORD-1 Riya Rs. 899 ORD-3 Kabir Rs. 1499 Total: Rs. 2398
What this code does
OrderReport.printis thefinaltemplate method: it holds the filter, sort, loop and sum once.- Each subclass supplies only the three lines that differed, and the output is exactly the same as before.
Marking print as final stops a subclass from changing the order of the steps. The filter, the sort and the loop now exist exactly once, so one fix reaches every report.
Order of execution
Refactor to a template method
Put the refactoring steps in a safe order.
Abstract steps and hooks
An abstract step is a method with no body in the base class. Every subclass must supply it, so the base class can call it without knowing what it does.
Differing parts become abstract steps, which every subclass must write, or hooks, which have a default. The code below has both: a required header() and an optional footer.
Example 3 · Abstract steps plus hooks
import java.util.ArrayList;import java.util.Comparator;import java.util.List;
record Order(String id, String customer, String status, int total) { }
abstract class OrderReport { final void print(List<Order> orders) { List<Order> chosen = new ArrayList<>(); for (Order o : orders) { if (o.status().equals("PAID") || includeCancelled()) chosen.add(o); } chosen.sort(Comparator.comparing(Order::id)); System.out.println(header()); int sum = 0; for (Order o : chosen) { System.out.println(row(o)); if (o.status().equals("PAID")) sum += o.total(); } System.out.println(totalLine(sum)); footer(); }
// Abstract steps: every report must supply them abstract String header(); abstract String row(Order o); abstract String totalLine(int sum);
// Hooks: sensible defaults that a report may override boolean includeCancelled() { return false; } void footer() { }}
class TextOrderReport extends OrderReport { String header() { return "Paid orders"; } String row(Order o) { return " " + o.id() + " " + o.customer() + " Rs. " + o.total(); } String totalLine(int sum) { return "Total: Rs. " + sum; }}
// New report for the accounts team: shows cancelled orders too, and signs offclass AccountsReport extends OrderReport { String header() { return "Accounts view"; } String row(Order o) { return " " + o.id() + " " + o.status() + " Rs. " + o.total(); } String totalLine(int sum) { return "Collected: Rs. " + sum; }
@Override boolean includeCancelled() { return true; }
@Override void footer() { System.out.println("-- checked by accounts --"); }}
public class HooksDemo { public static void main(String[] args) { List<Order> orders = List.of( new Order("ORD-3", "Kabir", "PAID", 1499), new Order("ORD-1", "Riya", "PAID", 899), new Order("ORD-2", "Meera", "CANCELLED", 60)); new TextOrderReport().print(orders); new AccountsReport().print(orders); }}Paid orders ORD-1 Riya Rs. 899 ORD-3 Kabir Rs. 1499 Total: Rs. 2398 Accounts view ORD-1 PAID Rs. 899 ORD-2 CANCELLED Rs. 60 ORD-3 PAID Rs. 1499 Collected: Rs. 2398 -- checked by accounts --
What this code does
includeCancelled()andfooter()are hooks with defaults, soTextOrderReportdid not change at all.AccountsReportoverrides both hooks to list cancelled orders and sign off, while the total still counts only paid ones.
A hook is a method with a sensible default, often empty or false, that a subclass may override: an optional footer, or "include cancelled orders".
Hooks let a new report change the skeleton at planned points without touching the base class or the other reports. Keep the number of hooks small; ten hooks make the base class hard to follow.
Fix the error
Use the hook, not the template
Read the real compiler error, then pick the line that fixes it.
Accounts wants cancelled orders too. Use the planned hook.
Error
AccountsReport.java:5: error: print(List<Order>) in AccountsReport cannot override print(List<Order>) in OrderReport
void print(List<Order> orders) { }
^
overridden method is finalAlternative: passing lambdas into one method
When only one or two small steps differ, pass them in as lambdas instead of subclassing. The method below takes the header, row and total as parameters.
Example 4 · The same reports with lambdas
import java.util.ArrayList;import java.util.Comparator;import java.util.List;import java.util.function.Function;import java.util.function.IntFunction;
record Order(String id, String customer, String status, int total) { }
class ReportPrinter { static void print(List<Order> orders, String header, Function<Order, String> row, IntFunction<String> totalLine) { List<Order> paid = new ArrayList<>(); for (Order o : orders) { if (o.status().equals("PAID")) paid.add(o); } paid.sort(Comparator.comparing(Order::id)); System.out.println(header); int sum = 0; for (Order o : paid) { System.out.println(row.apply(o)); sum += o.total(); } System.out.println(totalLine.apply(sum)); }}
public class LambdaReportsDemo { public static void main(String[] args) { List<Order> orders = List.of( new Order("ORD-3", "Kabir", "PAID", 1499), new Order("ORD-1", "Riya", "PAID", 899), new Order("ORD-2", "Meera", "CANCELLED", 60));
ReportPrinter.print(orders, "id,customer,total", o -> o.id() + "," + o.customer() + "," + o.total(), sum -> "TOTAL,," + sum); ReportPrinter.print(orders, "Paid orders", o -> " " + o.id() + " " + o.customer() + " Rs. " + o.total(), sum -> "Total: Rs. " + sum); }}id,customer,total ORD-1,Riya,899 ORD-3,Kabir,1499 TOTAL,,2398 Paid orders ORD-1 Riya Rs. 899 ORD-3 Kabir Rs. 1499 Total: Rs. 2398
What this code does
ReportPrinter.printkeeps the fixed steps and takes the header, row format and total line as parameters.- No subclasses are needed, which suits these small differences; the output matches the class version line for line.
This is Template Method by callback, the style of Spring's JdbcTemplate.
Choose lambdas when only one or two small steps differ and the variants need no state of their own. Choose a base class when there are several related steps, hooks, or variants worth naming, such as AccountsReport.
Checking the output is unchanged
Capturing output means pointing System.out at a ByteArrayOutputStream with System.setOut, so the text a program prints becomes a string that two versions can be compared on.
To prove the refactor kept behaviour, capture what each version prints and compare the two strings. The program below runs old and new on three different lists.
Example 5 · Proving the output did not change
import java.io.ByteArrayOutputStream;import java.io.PrintStream;import java.util.ArrayList;import java.util.Comparator;import java.util.List;
record Order(String id, String customer, String status, int total) { }
class OldTextReport { void print(List<Order> orders) { List<Order> paid = new ArrayList<>(); for (Order o : orders) { if (o.status().equals("PAID")) paid.add(o); } paid.sort(Comparator.comparing(Order::id)); System.out.println("Paid orders"); int sum = 0; for (Order o : paid) { System.out.println(" " + o.id() + " " + o.customer() + " Rs. " + o.total()); sum += o.total(); } System.out.println("Total: Rs. " + sum); }}
abstract class OrderReport { final void print(List<Order> orders) { List<Order> paid = new ArrayList<>(); for (Order o : orders) { if (o.status().equals("PAID")) paid.add(o); } paid.sort(Comparator.comparing(Order::id)); System.out.println(header()); int sum = 0; for (Order o : paid) { System.out.println(row(o)); sum += o.total(); } System.out.println(totalLine(sum)); }
abstract String header(); abstract String row(Order o); abstract String totalLine(int sum);}
class NewTextReport extends OrderReport { String header() { return "Paid orders"; } String row(Order o) { return " " + o.id() + " " + o.customer() + " Rs. " + o.total(); } String totalLine(int sum) { return "Total: Rs. " + sum; }}
public class SameOutputCheckDemo { // Runs some code and returns everything it printed static String capture(Runnable code) { PrintStream original = System.out; ByteArrayOutputStream buffer = new ByteArrayOutputStream(); System.setOut(new PrintStream(buffer, true)); try { code.run(); } finally { System.setOut(original); } return buffer.toString(); }
public static void main(String[] args) { List<List<Order>> testData = List.of( List.of(), List.of(new Order("ORD-2", "Meera", "CANCELLED", 60)), List.of(new Order("ORD-3", "Kabir", "PAID", 1499), new Order("ORD-1", "Riya", "PAID", 899)));
int set = 0; for (List<Order> orders : testData) { set++; String before = capture(() -> new OldTextReport().print(orders)); String after = capture(() -> new NewTextReport().print(orders)); System.out.println("Data set " + set + ": " + (before.equals(after) ? "same output" : "DIFFERENT")); } }}Data set 1: same output Data set 2: same output Data set 3: same output
What this code does
captureswapsSystem.outfor a buffer, runs the code, restoresSystem.outand returns what was printed.- The old and new reports print the same text for an empty list, a list with only a cancelled order and a normal list.
Test more than the happy path: an empty list, a list of only cancelled orders and a normal list. Always restore the original System.out in a finally block.
Next step
Check your understanding
12 quick questions