SteelReed

Search

Search posts, questions…

3. Advanced Java

Template Method or composition: refactoring a booking flow from v0 to v2

Three versions of a homestay booking flow: one transactional method that does everything, steps with if-checks on the listing type, then Template Method with a hook. Three rules that keep Template Method safe, the traps inside Spring (constructor injection, @SneakyThrows, self-invocation), and when to switch to composition.

18 Nov 20267 min readMid

–

Strategy in the previous post untangled a repeated if/else; this one handles several flows with the same order of steps that differ in a few. The example is v0, v1 and v2 of an Airbnb-style booking flow (Spring Boot 3, PostgreSQL), rewritten in plain Java for JDK 21. Read first: Abstract classes and interfaces.

1. The problem

The booking flow has seven steps. Apartments must check the building is open and notify its management, so a developer adds if (type == APARTMENT) to two steps. Resorts need a deposit, villas need owner confirmation: each new type adds a branch to every step, each time editing a class every type shares.

2. Key idea

Template Method is a preprinted form with the sections in order; each department fills a few boxes. Composition is a deck of rule cards: each listing type draws the cards it needs.

Criterion Template Method Composition (rules, listeners)
A variant is a subclass an assembled object
Change at runtime no yes
Combining "apartment + corporate + long stay" hard: one parent, subclass explosion easy
The whole flow in one place yes read the wiring
Constructor injection in Spring repeated in every subclass each rule declares its own dependencies

2.1 When to choose which?

Choice Use when Don't use when
Template Method 2–3 types, a stable skeleton, differences in a few steps subclasses override more than half the steps
Composition variants stack up, assembled by config a single variant: pointless indirection
abstract step a decision every type must make (how to confirm) optional extensions
Empty default hook extra notifications, publishing events required parts: forgetting an override runs the default

2.2 Where does Spring break it?

  • The template calls this.step(), bypassing the proxy: @Transactional(REQUIRES_NEW) on a step is silently ignored.
  • @SneakyThrows throws checked exceptions: Spring only rolls back on RuntimeException, so the transaction commits despite the error.
  • Constructor injection: each subclass must redeclare a constructor with every dependency.

3. In Java

JAVA
abstract class BookingTemplate {
    public final BookingResult book(Homestay h, BookingRequest r) { // final: order can't change
        validate(h, r);            // private: subclasses can't skip it
        checkExtraRules(h, r);     // extra-rules hook
        Booking b = lockAndPrice(h, r);
        afterBooked(b);            // optional hook
        return BookingResult.ok(b);
    }
    private void validate(Homestay h, BookingRequest r) {
        if (r.guests() > h.capacity()) throw new BookingException("GUESTS_INVALID");
    }
    protected void checkExtraRules(Homestay h, BookingRequest r) {}
    protected void afterBooked(Booking b) {}
    private Booking lockAndPrice(Homestay h, BookingRequest r) { /* FOR UPDATE, ORDER BY date */ }
}
// apartment, building closed: FAIL BUILDING_CLOSED
// villa (overrides nothing):  OK [nights locked, email guest]

Other languages: Go has no inheritance, so it only uses composition.

The same flow with composition
JAVA
interface BookingRule { void check(Homestay h, BookingRequest r); }
interface BookingListener { void onBooked(Booking b); }
 
record BookingPolicy(List<BookingRule> rules, List<BookingListener> listeners) {}
 
Map<ListingType, BookingPolicy> policies = Map.of(
    APARTMENT, new BookingPolicy(List.of(GUEST_LIMIT, BUILDING_OPEN), List.of(EMAIL_GUEST, EMAIL_BUILDING)),
    VILLA,     new BookingPolicy(List.of(GUEST_LIMIT), List.of(EMAIL_GUEST)));

The service constructor checks that every ListingType.values() has a policy, so missing config fails at startup (no policy for APARTMENT), not when a guest books.

4. Working with AI

Give the AI: splitting a long method into named steps, writing a parameterized test that runs for every subclass.

Check in AI-written code:

  • The template method is final; required steps are private.
  • No subclass overrides a required step and forgets super.
  • No @Transactional on a step called via this.
  • No @SneakyThrows inside a @Transactional method.

5. Exercises

Exercise 1: A subclass forgets super

ResortBooking extends BookingTemplate (an older version where checkAvailability is protected) overrides checkAvailability to check the deposit and never calls super.checkAvailability. ResortBooking's tests only cover the no-deposit case and pass. What bug reaches production, and how do you fix it?

Solution to Exercise 1

The guest-count vs capacity check (in the parent's checkAvailability) is skipped: resorts accept bookings over capacity.

  • Quick fix: call super.
  • Root fix: move the capacity check into a private step the template always calls; subclasses only implement the checkExtraRules hook.
  • Add a parameterized test that runs for every subclass to check invariant rules.

Exercise 2: Adding a tax-code rule

Corporate guests must have a valid tax code (10 digits, optionally - and a 3-digit branch), for every listing type. The AI proposes CorporateApartmentBooking and CorporateVillaBooking. Which way do you go?

Solution to Exercise 2

No new subclasses: two types today become 2 × N classes tomorrow. Use composition: write a TAX_CODE_REQUIRED rule (skipped for non-corporate guests) and add it to every policy's rule list. No changes to old rules or to BookingService.

Check four cases: regular guest needs no code; corporate without code → TAX_CODE_REQUIRED; valid code → booked; valid code but too many guests → GUESTS_INVALID (old rules still run).

Summary

  • Template Method: the parent fixes the order, subclasses change a few steps.
  • Template final, required steps private, extensions as hooks.
  • In Spring: @Transactional on a step is ignored; @SneakyThrows commits on error.
  • When variants combine or subclasses override over half the steps, move to composition.

Read more: Adapter and Factory.

Practice interview questions on this topic

All OOP & Design questions →

Loading comments…