Template Method
- Intent
- Define the skeleton of an algorithm in one method and let subclasses redefine only some steps, without changing the order or the rest.
- Application
- Importing results from a CSV or from a partner's app is the same process with one different step. Fix the skeleton once and let each format fill in only its own part.
The coach sends results.csv to ResultImportController. Next to it are CopyPasteCsvImporter and CopyPasteJsonImporter, both highlighted, and both save into ResultRepository.
The partner app sends score: 0 to the controller, which passes it to CopyPasteJsonImporter, highlighted; the INSERT into ResultRepository fails.
The abstract ResultImporter appears, highlighted, saving into ResultRepository. The copied importers are gone.
CsvResultImporter and JsonResultImporter appear highlighted, both with inheritance arrows pointing to ResultImporter.
The Spring context appears under the whole diagram; the controller is highlighted together with the context, connected to both importers.
results.csv travels from the coach to the controller, importAll() from the controller to CsvResultImporter, and save ×2 from ResultImporter, highlighted, to ResultRepository.
The partner app sends JSON to the controller, which calls importAll() on JsonResultImporter, highlighted.
Inside the Spring context there are ResultRepository and JdbcTemplate, highlighted; the repository sends it query(sql, rowMapper).
Final view: the coach and the partner, the controller, both importers extending ResultImporter and the repository, all inside the Spring context.
Step 1 of 9
Two importers, the same code
The box gets results from two places. Coaches upload a CSV after each class, and a partner's app sends them as JSON.
Each format has its own importer, written start to finish: read, turn every row into a Result, validate, save and count. Notice that only the first step depends on the format; the rest is identical.
Step 2 of 9
The fix that reached only one copy
Someone added a rule: a score must be greater than 0. They put it in the CSV importer… and forgot the JSON one.
The partner sends a result with score: 0. The JSON importer doesn't check it, and only the database's CHECK constraint stops it, with an ugly error instead of a clean rejection.
Step 3 of 9
A skeleton nobody touches
Template Method moves the process into a base class, ResultImporter, whose importAll() method fixes the steps and their order:
parse(payload), the part that varies with the format.- Validate every result, with the rule written only once.
- Save the valid ones and note the rejected ones.
afterImport(report), an optional step.
importAll() is final: no subclass can skip validation or change the order. And the save loop runs inside a TransactionTemplate: either every valid row is saved, or none is.
Step 4 of 9
Each format fills its gap
Now every format is a subclass with a single required method:
CsvResultImporter.parse()checks the header, skips it and splits each line on commas.JsonResultImporter.parse()lets Jackson turn the JSON into a list ofResult.
Neither of them validates or saves anything: the base class already does. The score > 0 rule now covers both formats, and the next one too.
Step 5 of 9
Two beans, one endpoint
Both subclasses are ordinary beans (@Component). The controller gets them through its constructor and has one method per format; Spring MVC picks which one to call from the request's Content-Type (the consumes attribute):
text/csvgoes tocsv.importAll(...).application/jsongoes tojson.importAll(...).
Both calls hit the same template method; the only difference is which subclass fills in the parse step.
Step 6 of 9
A CSV start to finish
The coach uploads the CSV for the 18:00 class with three rows: Ana with 185, Leo with 0 and Mia with 21.
- The controller calls
importAll()onCsvResultImporter. parse()turns the lines into threeResults.- The shared validation step rejects Leo:
score must be > 0. - Ana and Mia are saved, and the API returns
{imported: 2, rejected: ["Leo/Fran: score must be > 0"]}.
Step 7 of 9
An optional step
Only the partner integration needs something extra: keeping the last report so its app can poll it with GET /api/results/import/partner/last. That's what the afterImport() hook is for. In the base class it does nothing, and JsonResultImporter overrides it.
Step 8 of 9
Spring already does it for you
JdbcTemplate is one big Template Method. It fixes the usual part: get a connection, prepare the statement, run it, loop over the ResultSet, close everything and translate SQL errors into Spring exceptions.
You only supply what varies: the SQL and a RowMapper that says how to turn one row into a Result. But you don't extend anything: the variable step arrives as a lambda. It's the "callback" version of the same pattern.
Step 9 of 9
Recap
You started with two copied importers that no longer matched and ended up with:
- One skeleton,
importAll(),finaland written once. - One abstract step,
parse(), that each format implements. - One hook,
afterImport(), for whoever needs something extra. - The shared rules, in one place, for every format.
Code
CopyPasteCsvImporter.java
public int importAll(String csv) {
int saved = 0;
String[] lines = csv.strip().split("\\R");
for (int i = 1; i < lines.length; i++) {
String[] cols = lines[i].split(","); // parse
Result r = new Result(cols[0], cols[1], Integer.parseInt(cols[2].strip()));
if (r.athlete().isBlank() || r.score() <= 0) { // validate
continue;
}
results.save(r); // save
saved++;
}
return saved;
}CopyPasteJsonImporter.java
public int importAll(String[][] rows) {
int saved = 0;
for (String[] row : rows) {
Result r = new Result(row[0], row[1], Integer.parseInt(row[2])); // parse
// validate? the score check was added to the CSV copy... and forgotten here
results.save(r); // save
saved++;
}
return saved;
}ResultImporter.java
public final ImportReport importAll(String payload) {
List<Result> parsed = parse(payload); // 1. varies: CSV, JSON...
ImportReport report = tx.execute(status -> { // all rows or none
int imported = 0;
List<String> rejected = new ArrayList<>();
for (Result r : parsed) {
Optional<String> problem = validate(r); // 2. shared rule, written once
if (problem.isPresent()) {
rejected.add(r.athlete() + "/" + r.wod() + ": " + problem.get());
continue;
}
results.save(r); // 3. shared
imported++;
}
return new ImportReport(imported, rejected);
});
afterImport(report); // 4. hook: optional extra step
return report;
}
protected abstract List<Result> parse(String payload);
protected void afterImport(ImportReport report) {
// hook: does nothing unless a subclass needs it
}CsvResultImporter.java
@Override
protected List<Result> parse(String payload) {
List<Result> rows = new ArrayList<>();
String[] lines = payload.strip().split("\\R");
requireHeader(lines[0]);
for (int i = 1; i < lines.length; i++) { // line 1 is the header
String[] cols = lines[i].split(",", -1); // simple CSV: no quoted commas in names
if (cols.length != 3) {
throw new IllegalArgumentException("line " + (i + 1) + ": expected athlete,wod,score");
}
rows.add(new Result(cols[0].strip(), cols[1].strip(), parseScore(cols[2], i + 1)));
}
return rows;
}ResultImportController.java
@PostMapping(path = "/api/results/import", consumes = "text/csv")
public ImportReport importCsv(@RequestBody String body) {
return csv.importAll(body); // same algorithm...
}
@PostMapping(path = "/api/results/import", consumes = "application/json")
public ImportReport importJson(@RequestBody String body) {
return json.importAll(body); // ...different parse step
}ResultImporterTest.java
ImportReport report = csv.importAll("""
athlete,wod,score
Ana,Fran,185
Leo,Fran,0
Mia,Cindy,21
""");
// the shared validation step rejected Leo's 0 for both formats alike
assertThat(report.imported()).isEqualTo(2);
assertThat(report.rejected()).containsExactly("Leo/Fran: score must be > 0");JsonResultImporter.java
@Override
protected void afterImport(ImportReport report) {
// only the partner integration needs this: keep the last report so its app can poll it
lastPartnerReport = report;
}ResultRepository.java
public List<Result> findByWod(String wod) {
// JdbcTemplate runs the fixed part (connection, statement, loop, close, error translation);
// you only supply the SQL and how to turn one row into a Result
return jdbc.query(
"SELECT athlete, wod, score FROM result WHERE wod = ? ORDER BY score, athlete",
(rs, rowNum) -> new Result(rs.getString("athlete"), rs.getString("wod"), rs.getInt("score")),
wod);
}ResultImporter.java
public final ImportReport importAll(String payload) {
List<Result> parsed = parse(payload); // 1. varies: CSV, JSON...
ImportReport report = tx.execute(status -> { // all rows or none
int imported = 0;
List<String> rejected = new ArrayList<>();
for (Result r : parsed) {
Optional<String> problem = validate(r); // 2. shared rule, written once
if (problem.isPresent()) {
rejected.add(r.athlete() + "/" + r.wod() + ": " + problem.get());
continue;
}
results.save(r); // 3. shared
imported++;
}
return new ImportReport(imported, rejected);
});
afterImport(report); // 4. hook: optional extra step
return report;
}
protected abstract List<Result> parse(String payload);
protected void afterImport(ImportReport report) {
// hook: does nothing unless a subclass needs it
}