Design patterns through refactoring series: 1. Strategy · 2. Template Method and composition · 3. Observer and Spring events · 4. Adapter and Factory
The previous post used Strategy to untangle a repeated if/else. This one deals with a related smell, several flows with the same order of steps that differ in only a few of them, across versions v0, v1 and v2 of an Airbnb-style booking flow (Spring Boot 3, PostgreSQL) from the course’s sample code, rewritten in plain Java for JDK 21. Afterwards you can write a safe Template Method, avoid three traps inside Spring, and tell when to switch to composition.
Read first: UML and relationships between classes (the composition over inheritance part) and Abstract classes and interfaces.
1. v0: one transactional method does everything
Key idea: v0 is one @Transactional method that runs seven steps top to bottom. With a single kind of listing that’s fine: you read it once and you get it.
The homestay_availability table has one row per night per homestay (price and status for that night). The seven steps:
- Validate the request: check-in not in the past, check-in not after check-out, more than 0 guests.
- Validate the homestay: it exists, it’s
ACTIVE, guests don’t exceed capacity. - No more than 365 nights.
- Load and lock the free availability rows in the date range (
@Lock(PESSIMISTIC_WRITE), i.e.SELECT ... FOR UPDATE); if any night is missing, answerHOMESTAY_BUSY. - Compute the price (sum of nightly prices, minus the long-stay discount).
- Build the booking, mark the nights
BOOKED, save. - Send an email (just a log line in the sample).
Splitting v0 into well-named steps, with each function staying at one level of abstraction, is a clean code technique before it is a pattern; see Clean code: naming, functions and control flow.
A note on the row locking in step 4
The locking deserves its own post: two overlapping bookings wait for each other on FOR UPDATE. Add ORDER BY date so two overlapping ranges don’t lock rows in different orders and deadlock; see Transactions, isolation levels and locking.
2. v1: split into steps, but if on the type starts to spread
Key idea: v1 splits v0 into protected methods, but each new listing type is handled with an if on the type in several steps. That’s the “switch on type” smell.
New requirement: apartments sit inside buildings. Before holding the nights we must check the building is open, and after booking we must notify building management. v1 splits v0 into validateRequest, validateHomestay, checkAvailability, buildBooking, sendNotifications, and adds this to two of them:
if (ListingType.of(homestay.getType()) == ListingType.APARTMENT) {
log.info("Checking the status of the building...");
}
One question about the type shows up in several steps. A third type (a resort that needs a deposit, a villa that needs the owner’s confirmation) will add a branch to every one of those steps. Each time, you edit a class that every type depends on.
3. v2: Template Method
Key idea: Template Method keeps the order of steps in the parent inside one fixed method (the template), and subclasses change only the content of some steps. Three rules make it safe: a final template, private invariant steps, and abstract steps kept apart from hooks.
The repo’s v2:
BaseBookingService.executeis the skeleton; the emptypostProcessmethod is a hook (an optional extension point).ApartmentBookingServiceoverrides the availability check, the notification step and the hook (publishing an event to Kafka).VillaBookingServiceoverrides nothing.BookingFactorypicks the service by listing type.
classDiagram
class BookingService {
<<interface>>
+execute(request) BookingResponse
}
class BaseBookingService {
+execute(request) BookingResponse
#validateRequest(request)
#validateHomestay(request) Homestay
#checkAvailability(homestay, request)
#sendNotifications(booking)
#postProcess(booking)
}
class ApartmentBookingService {
#checkAvailability(homestay, request)
#sendNotifications(booking)
#postProcess(booking)
}
class VillaBookingService
class BookingFactory {
+build(request) BookingService
}
BookingService <|.. BaseBookingService
BaseBookingService <|-- ApartmentBookingService
BaseBookingService <|-- VillaBookingService
BookingFactory ..> BookingService : picks by type
My version, without Spring or a database so it runs with java TemplateDemo.java:
static abstract class BookingTemplate {
protected final List<String> log = new ArrayList<>();
/** The skeleton. final: subclasses may change steps, never the order. */
public final Booking book(BookingRequest r) {
validate(r);
Homestay h = load(r.homestayId());
checkAvailability(h, r); // overridable step
Booking b = new Booking(r.requestId(), h.id(), r.nights());
notifyParties(b); // overridable step
afterBooked(b); // hook: empty by default
return b;
}
private void validate(BookingRequest r) { // invariant step: private
if (r.nights() <= 0 || r.nights() > 365) throw new BusinessException("NIGHTS_INVALID");
if (r.guests() <= 0) throw new BusinessException("GUESTS_INVALID");
}
private Homestay load(long id) {
Homestay h = HOMESTAYS.get(id);
if (h == null) throw new BusinessException("HOMESTAY_NOT_FOUND");
return h;
}
protected void checkAvailability(Homestay h, BookingRequest r) {
if (r.guests() > h.maxGuests()) throw new BusinessException("GUESTS_INVALID");
log.add("nights locked for homestay " + h.id());
}
protected void notifyParties(Booking b) { log.add("email guest"); }
protected void afterBooked(Booking b) { }
}
static final class DefaultBooking extends BookingTemplate { }
static final class ApartmentBooking extends BookingTemplate {
@Override protected void checkAvailability(Homestay h, BookingRequest r) {
if (!h.buildingOpen()) throw new BusinessException("BUILDING_CLOSED");
super.checkAvailability(h, r); // forgetting this line silently skips the guest check
}
@Override protected void notifyParties(Booking b) {
super.notifyParties(b);
log.add("email building management");
}
@Override protected void afterBooked(Booking b) { log.add("publish BookingCreated"); }
}
apartment, building closed: FAIL BUILDING_CLOSED
apartment, open: OK [nights locked for homestay 3, email guest, email building management, publish BookingCreated]
villa via default: OK [nights locked for homestay 2, email guest]
too many guests: FAIL GUESTS_INVALID
Three rules that keep Template Method safe:
- The template method is
final. If a subclass can overridebook, it can skip validation. (The sample leavesexecutenon-final.) - Invariant steps are
private. Only open up (protected) the steps that are genuinely allowed to differ. - Separate abstract steps from hooks. A step every subclass must implement is
abstract; a hook is an empty default a subclass may implement (afterBookedhere). It’s the Hollywood principle at class level: the parent calls the child, not the other way round.
Abstract or hook: what each choice costs
The constructor trap: a parent calling a method the subclass overrides
4. Template Method inside Spring: where it breaks
Key idea: putting the hierarchy into Spring creates three bugs the UML doesn’t show: constructor injection repeated in every subclass, @SneakyThrows committing a failed transaction, and @Transactional on a step being ignored.
Constructor injection and inheritance don’t get along. BaseBookingService needs five dependencies (two repositories, HomestayService, PricingService, a mapper). With constructor injection, every subclass has to redeclare a constructor taking all five and call super(...); Lombok can’t generate a super call with arguments. The sample sidesteps this by leaving the fields non-final and keeping @RequiredArgsConstructor, so Spring injects nothing and the first request hits a NullPointerException.
Why @RequiredArgsConstructor generates an empty constructor: checked with Lombok 1.18.42
Lombok only puts final fields in the constructor, so with no final fields the generated constructor has no parameters. I checked this with Lombok 1.18.42:
- A class with one
finalfield and one plain field: the constructor takes only thefinalone. - A class with no
finalfields: an empty constructor.
The full analysis (and how to review it) is in part 4: Adapter and Factory and in the worked review of the booking flow.
Rollback with @SneakyThrows. execute has @SneakyThrows and jakarta.transaction’s @Transactional. By default both Spring and JTA roll back only on RuntimeException or Error. A checked exception “sneaked” out through @SneakyThrows is still checked, so the transaction commits even though the method failed. Fix: drop @SneakyThrows, or declare rollbackFor = Exception.class (Spring) / rollbackOn = Exception.class (JTA).
5. Template Method or composition?
Key idea: with Template Method a variant is a subclass; with composition a variant is a list of rules and listeners wired per type. Composition wins once variants start combining.
The same behaviour as section 3, written with composition:
interface BookingRule { void check(Homestay h, BookingRequest r); }
interface BookingListener { void onBooked(Booking b, List<String> log); }
static final BookingRule GUEST_LIMIT = (h, r) -> {
if (r.guests() > h.maxGuests()) throw new BusinessException("GUESTS_INVALID");
};
static final BookingRule BUILDING_OPEN = (h, r) -> {
if (!h.buildingOpen()) throw new BusinessException("BUILDING_CLOSED");
};
static final BookingListener EMAIL_GUEST = (b, log) -> log.add("email guest");
static final BookingListener EMAIL_BUILDING = (b, log) -> log.add("email building management");
static final BookingListener PUBLISH = (b, log) -> log.add("publish BookingCreated");
record Policy(List<BookingRule> rules, List<BookingListener> listeners) {}
static final class BookingService {
private final Map<ListingType, Policy> policies;
BookingService(Map<ListingType, Policy> policies) {
for (ListingType t : ListingType.values())
if (!policies.containsKey(t)) throw new IllegalStateException("no policy for " + t);
this.policies = new EnumMap<>(policies);
}
Booking book(BookingRequest r, List<String> log) {
Homestay h = HOMESTAYS.get(r.homestayId());
if (h == null) throw new BusinessException("HOMESTAY_NOT_FOUND");
Policy p = policies.get(h.type());
p.rules().forEach(rule -> rule.check(h, r));
log.add("nights locked for homestay " + h.id());
Booking b = new Booking(r.requestId(), h.id(), r.nights());
p.listeners().forEach(l -> l.onBooked(b, log));
return b;
}
}
composition, apartment: OK [nights locked for homestay 3, email guest, email building management, publish BookingCreated]
startup check: no policy for APARTMENT
The constructor checks that every type has a policy, so missing configuration fails at startup, not when a guest clicks “book”.
| Criterion | Template Method | Composition (Strategy/rules) |
|---|---|---|
| A variant is | a subclass | a set of wired objects |
| Change at runtime | no | yes |
| Combining several variants | hard (one parent) | easy |
| Whole flow visible in one place | yes | read the wiring |
| Constructor injection in Spring | repeated in every subclass | each rule declares its own |
6. Who picks the subclass?
Key idea: a BookingFactory loads the homestay and switches on its type to pick the subclass. Its comment says “Abstract Factory”, but it’s really a simple factory.
The factory has two bugs worth learning from: a default branch that hides new types, and dependencies that never get injected. The analysis is in part 4: Adapter and Factory.
Exercises
Exercise 1: Add “corporate guests need a tax code” without touching existing rules
Task: with the composition design from section 5, add a requirement: corporate bookings must carry a valid tax code (10 digits, optionally - plus a 3-digit branch), for every listing type. Don’t edit existing rules or BookingService.
Solution to Exercise 1: one new rule, new wiring
interface BookingRule {
void check(Homestay h, BookingRequest r);
default BookingRule andThen(BookingRule next) {
return (h, r) -> { check(h, r); next.check(h, r); };
}
}
static final BookingRule CORPORATE_NEEDS_TAX_CODE = (h, r) -> {
if (r.corporate() && r.companyTaxCode().filter(code -> code.matches("\\d{10}(-\\d{3})?")).isEmpty())
throw new BusinessException("TAX_CODE_REQUIRED");
};
// only the wiring changes
var service = new BookingService(Map.of(
ListingType.APARTMENT, GUEST_LIMIT.andThen(CORPORATE_NEEDS_TAX_CODE),
ListingType.VILLA, GUEST_LIMIT.andThen(CORPORATE_NEEDS_TAX_CODE)));
BOOKED APARTMENT
FAIL TAX_CODE_REQUIRED
BOOKED APARTMENT
FAIL GUESTS_INVALID
The four lines: a regular guest needs no code; a corporate guest without a code; with a valid code; with a code but too many guests (the old rule still runs).
With Template Method, the same requirement forces you to edit the parent or create a combined subclass per type. That’s why composition wins once variants start to add up.
Exercise 2: Find the bug in a subclass
Task: a ResortBooking extends BookingTemplate overrides checkAvailability to check that the guest has paid a deposit, and doesn’t call super.checkAvailability. ResortBooking’s tests only cover the “no deposit” case and they all pass. What bug reaches production?
Solution to Exercise 2
The guest-capacity check (inside the parent’s checkAvailability) is skipped for resorts, so resorts accept bookings over capacity.
- Quick fix: call
super. - Root fix: move the capacity check into a
privatestep the template always calls, and let subclasses implement only acheckExtraRuleshook. - Add a test that runs against every subclass (a parameterised test) to check the invariant rules.
Remember
- Explain how Template Method differs from Strategy (inheritance or composition, chosen at compile time or at runtime).
- State the three rules that keep Template Method safe, and why a forgotten
superis a silent bug. - Know when to use an abstract step and when to use a hook.
- Explain why
@Transactionalon a step is ignored and why@SneakyThrowslets a failed transaction commit. - Know which signs tell you to move from Template Method to composition.
Interview questions
Junior
What is Template Method and how does it differ from Strategy?
Template Method uses inheritance to fix the order of steps; Strategy uses composition to swap a whole behaviour, even at runtime.
Template Method fixes the order of steps in one method of a parent class, and subclasses override some steps; the variant is chosen at compile time (which subclass you instantiate). With Strategy, the object receives an implementation through a constructor or setter, it can change at runtime, and strategies can be combined.
Mid
What is a hook method, and how is it different from an abstract step?
A hook has a default (often empty) that a subclass may override; an abstract step is one every subclass must implement.
The template calls the hook at a fixed point, for example afterBooked to publish an event. Use hooks for optional extensions and abstract steps for decisions every variant has to make.
Why shouldn’t the template method be overridable?
Because Template Method’s value is guaranteeing the order and the mandatory steps; an overridable template lets a subclass skip them.
The mandatory steps are things like validation, locking and logging. Declare the template final, invariant steps private, and open only the steps that are allowed to vary.
Why shouldn’t a constructor call an overridable method?
Because the parent constructor runs before the subclass’s fields are assigned, so the overriding method sees its fields as null or 0.
That includes final fields that aren’t compile-time constants. The compiler doesn’t catch it, and it only bites in subclasses that use their fields. If initialisation needs a template step, use an init() method called after construction, or @PostConstruct in Spring.
Senior
When do you choose composition over Template Method?
When variants start combining, when subclasses override more than half the steps, when behaviour has to change by configuration at runtime, or when constructor injection is repeated in every subclass.
An example of combining: apartment and corporate guest and long stay. Composition turns each rule into a small bean, tested alone, wired per type. The price is that the overall flow no longer sits in one place, so I usually keep an orchestrating service that reads like a template method but calls injected rules.
A template step has @Transactional(propagation = REQUIRES_NEW) but no new transaction appears. Why?
Self-invocation: the template calls the step as this.step(), bypassing Spring’s proxy, so the annotation is ignored.
Fix it by moving the step into another bean that gets injected, or by using a TransactionTemplate inside the step. Also check: private and final methods can’t be intercepted by a CGLIB proxy either.
A service has both @SneakyThrows and @Transactional. What’s the risk?
A checked exception sneaked out through @SneakyThrows doesn’t trigger a rollback, so the transaction commits even though the method failed halfway.
By default Spring and JTA only roll back on unchecked exceptions. Example damage: nights marked booked but the booking not fully saved. Fix: drop @SneakyThrows and wrap into an unchecked business exception, or declare rollbackFor = Exception.class.
Useful phrases for interviews
- “I keep the template method final and the invariant steps private, so subclasses can’t skip validation.”
- “The hook is empty by default; only apartments override it to publish an event.”
- “Once variants started combining, a subclass per combination stopped scaling, so we moved to composable rules.”
- “That annotation was ignored because the template calls the step through
this, not through the proxy.” - “With
@SneakyThrows, a checked exception escapes without triggering a rollback.” - “A parameterised test runs the invariant rules against every subclass.”
Notes based on the Advanced Backend course (Ronin Engineer), rewritten in my own words.