Template Method and Chain of Responsibility

Mid-level Frequently asked 5 min

On this page

The question

Where does Spring use Template Method and Chain of Responsibility?

30-second answer

Template Method: OncePerRequestFilter has a final doFilter that calls your doFilterInternal, and AbstractApplicationContext.refresh() calls hooks such as onRefresh(). Chain of Responsibility: servlet filters, including Spring Security's filter chain, where each filter calls chain.doFilter or stops the request. JdbcTemplate is a related form: it fixes the JDBC (Java Database Connectivity) steps and takes your code as a callback.

Understand it

A request through a handler chain

Step by step

A POST /orders request arrives with a token. It enters the chain at the first handler, not at the controller.

Step 1 of 6
View as text

Three handlers in a row, Logging, Authentication and Controller, with a request moving through them. Arrows go forward along the top and back along the bottom.

A POST /orders request arrives with a token. It enters the chain at the first handler, not at the controller. The request waits on the left.

Logging notes the request and calls next. Each handler knows only the next one, never the whole chain. Logging is highlighted.

Authentication checks the token. It is valid, so this handler also calls next. Authentication is highlighted.

The last link is the controller. It runs only because every handler before it chose to call next. The controller is highlighted.

The response travels back through the same handlers in reverse, so Logging can also record the 200 status. The request travels back, labelled 200.

A request with no token: Authentication returns 401 and never calls next. The controller does not run, and Logging still sees the response. The controller fades, and a mark reads 401, stopped by Authentication.

Three handlers in a row, Logging, Authentication and Controller, with a request moving through them. Arrows go forward along the top and back along the bottom.

A POST /orders request arrives with a token. It enters the chain at the first handler, not at the controller. The request waits on the left.

Logging notes the request and calls next. Each handler knows only the next one, never the whole chain. Logging is highlighted.

Authentication checks the token. It is valid, so this handler also calls next. Authentication is highlighted.

The last link is the controller. It runs only because every handler before it chose to call next. The controller is highlighted.

The response travels back through the same handlers in reverse, so Logging can also record the 200 status. The request travels back, labelled 200.

A request with no token: Authentication returns 401 and never calls next. The controller does not run, and Logging still sees the response. The controller fades, and a mark reads 401, stopped by Authentication.

Takeaway: Each handler does its job and decides whether to call the next one, so a handler can stop a request before it ever reaches the controller.

Put the filters in order

Build

Put the filters in order so that each one has what it needs. Every position says why it comes where it does.

Drag a piece, or select it and then select a place.

View as text

A vertical chain of five filter positions, joined by arrows from top to bottom. Put the filters in order so that each one has what it needs. Every position says why it comes where it does.

The right order is: Logging, because it must also record rejected requests. Authentication, which works out who is calling. Authorization, which needs to know who, to decide if they may. Validation, which checks the body only for allowed callers. Controller, which runs only if every filter called next.

Who comes before may. Each filter can stop the request with its own status, and only a request that passes all of them reaches the controller. Once solved, each filter that can stop a request shows its status: Authentication 401, Authorization 403 and Validation 400.

A vertical chain of five filter positions, joined by arrows from top to bottom. Put the filters in order so that each one has what it needs. Every position says why it comes where it does.

The right order is: Logging, because it must also record rejected requests. Authentication, which works out who is calling. Authorization, which needs to know who, to decide if they may. Validation, which checks the body only for allowed callers. Controller, which runs only if every filter called next.

Who comes before may. Each filter can stop the request with its own status, and only a request that passes all of them reaches the controller. Once solved, each filter that can stop a request shows its status: Authentication 401, Authorization 403 and Validation 400.

Takeaway: Filter order is logic: logging sees everything, authentication comes before authorization, and validation runs only for callers who are allowed.

Template Method fixes the stepsThe final method run in the base class calls read, then format, then the optional hook afterFormat. A subclass supplies read and format and may override the hook, but it cannot change the order.run(): final, in thebase classread(): the subclasssupplies itformat(): thesubclass supplies itafterFormat():optional hook
Template Method fixes the stepsThe final method run in the base class calls read, then format, then the optional hook afterFormat. A subclass supplies read and format and may override the hook, but it cannot change the order.run(): final, in thebase classread(): the subclasssupplies itformat(): thesubclass supplies itafterFormat():optional hook
Template Method: the base class fixes the steps

In code

abstract class ReportJob {
    final String run() {                       // the template: fixed steps, final
        String raw = read();
        String body = format(raw);
        return afterFormat(body);
    }

    abstract String read();                    // a required step
    abstract String format(String raw);        // a required step
    String afterFormat(String body) { return body; }   // a hook: optional override
}

class CsvReportJob extends ReportJob {
    @Override String read() { return "a,b"; }
    @Override String format(String raw) { return raw.replace(',', ';'); }
}

new CsvReportJob().run();   // "a;b"
Template Method: fixed steps, subclass fills the gaps
interface Chain { String proceed(Request request); }
interface Handler { String handle(Request request, Chain next); }

static Chain chainOf(List<Handler> handlers, Function<Request, String> controller) {
    Chain chain = controller::apply;
    for (int i = handlers.size() - 1; i >= 0; i--) {
        Handler handler = handlers.get(i);
        Chain next = chain;
        chain = request -> handler.handle(request, next);
    }
    return chain;
}

Handler auth = (request, next) ->
    request.token() == null ? "401" : next.proceed(request);    // stops the chain
Chain of Responsibility: each handler decides whether to call next
// Template Method: final doFilter fixes the steps, and you supply doFilterInternal.
class AuditFilter extends OncePerRequestFilter {
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
                                    FilterChain chain) throws ServletException, IOException {
        chain.doFilter(request, response);    // Chain of Responsibility: call next
    }
}

// JdbcTemplate fixes the steps too, but takes a callback rather than a subclass.
List<String> names = jdbcTemplate.query("select name from orders", (rs, rowNum) -> rs.getString("name"));
Where Spring and the servlet API use them
A request with no token stops at AuthenticationA request with no token reaches Logging, which calls next. Authentication returns 401 and never calls next, so the controller does not run. Logging sees the 401 on its way back, and the client receives it.no nextPOST /orders, notokenLogging calls nextAuth returns 401Controllernever runsLogging sees 401Client gets 401
A request with no token stops at AuthenticationA request with no token reaches Logging, which calls next. Authentication returns 401 and never calls next, so the controller does not run. Logging sees the 401 on its way back, and the client receives it.no nextPOST /orders, notokenLogging calls nextAuth returns 401Controllernever runsLogging sees 401Client gets 401
A request with no token stops at Authentication

Solve it

Run fraud checks cheapest first and stop at the first rejection

A payment passes three fraud checks: a blocklist lookup (1 ms), a velocity check against Redis (5 ms) and a machine learning score (200 ms). Any rejection ends the process. Operations wants to reorder or add checks without a deploy of the payment code.

  1. Read the requirements as a shape. Ordered handlers, each may stop the flow, and the order is configuration: Chain of Responsibility.
  2. Define one handler type. FraudCheck.check(payment) returns APPROVE or REJECT. The chain walks the checks and stops at the first rejection.
  3. Order by cost. Cheap checks first, so most fraud is rejected before the 200 ms call.
  4. Make the order data. In Spring, inject List<FraudCheck>; @Order sets the sequence, and a new check is a new bean.
  5. Check. When the blocklist rejects, verify with Mockito that the scoring check was never called.
enum Verdict { APPROVE, REJECT }
interface FraudCheck { Verdict check(Payment payment); }

@Component @Order(1)
class BlocklistCheck implements FraudCheck {   // 1 ms; VelocityCheck (5 ms) is @Order(2), ScoreCheck (200 ms) @Order(3)
    private final Set<String> blocked;
    BlocklistCheck(Set<String> blocked) { this.blocked = blocked; }
    public Verdict check(Payment p) { return blocked.contains(p.cardHash()) ? Verdict.REJECT : Verdict.APPROVE; }
}

@Service
class FraudChain {
    private final List<FraudCheck> checks;                 // injected in @Order order
    FraudChain(List<FraudCheck> checks) { this.checks = checks; }

    Verdict evaluate(Payment payment) {
        for (FraudCheck check : checks) {
            if (check.check(payment) == Verdict.REJECT) return Verdict.REJECT;   // later checks never run
        }
        return Verdict.APPROVE;
    }
}
The chain stops at the first rejection

How to answer

  • Template Method: a base class fixes the steps, and subclasses fill in some of them.
  • Chain of Responsibility: each handler does its part and decides whether to pass the request on.
  • JdbcTemplate is a concrete class using callbacks, so nothing subclasses it.
  • HttpServlet.service() calling doGet() is the classic servlet example.

Common mistakes

  • Calling JdbcTemplate a pure Template Method; it uses callbacks, not inheritance.
  • Thinking every handler in a chain must run; any of them can stop the request.

Follow-up questions

What is the Template Method pattern, and what is its main risk?

A base class defines the steps of an algorithm in a final method and leaves some steps abstract, so subclasses vary the details without changing the order. The risk is inheritance itself: subclasses are tied to the base class, and they can only vary by overriding. If the step could be passed in as an object, Strategy or a callback is usually more flexible.

  • Making the template method final protects the order of the steps.
  • In the JDK (Java Development Kit), AbstractList needs only get and size; the rest is built from them.
  • Many subclass overrides can make the flow hard to follow.

See it in the infographic: A request through a handler chain

Why does the order of filters in a chain matter?

Each filter relies on what ran before it. Authorization needs the identity that authentication found, so reversing them rejects everyone or checks nothing. Logging has to come first to record requests that are later rejected. Validation should come after authorization, so unauthorized callers get no feedback about the body. In Spring, you set the order with @Order or addFilterBefore.

  • An early filter that stops a request saves the work of all later ones.
  • Authentication answers who you are; authorization answers what you may do.
  • Filters also run on the way back, in reverse order.

See it in the infographic: Put the filters in order

How is Chain of Responsibility different from Decorator?

They look alike: each object holds the next one and forwards to it. A Decorator always forwards, since its job is to add behavior around a target that always runs. A handler in a chain may stop and return, so the end of the chain might never run. A servlet filter can do both, so ask whether the design expects the call to be stopped.

  • Decorator guarantees that the target runs.
  • A chain does not guarantee that any given handler runs.
  • Chains are usually assembled from configuration, and decorators by the code that uses them.

See it in the infographic: A request through a handler chain

Does every handler in a Chain of Responsibility have to handle the request?

No, and there are two common forms. In the GoF (Gang of Four) form, exactly one handler deals with the request and the others pass it along. In the filter form, every handler does some work and passes it on, and any one can stop it. Servlet filters use the second form.

What is a hook method in Template Method?

A step with a default that does nothing or does something sensible, so a subclass may override it but need not. An abstract step must be implemented. afterFormat(body) returning body unchanged is a hook, and AbstractApplicationContext.onRefresh() is a hook that Spring Boot overrides to create the embedded web server.

Check yourself

1. A chain runs Logging, then Authentication, then the controller. A request arrives with no token, and Authentication returns 401 without calling next. Which ones ran?
Show answers
  • Logging and Authentication: Correct. Logging runs first and passes it on, and Authentication stops the request there.
  • All three: Incorrect. Authentication never called next, so the controller does not run.
  • Only Authentication: Incorrect. Logging comes first in the chain, so it had already run.
2. Which filter must run before Authorization?
Show answers
  • Authentication: Correct. Authorization decides what a caller may do, so it needs to know who the caller is.
  • The controller: Incorrect. The controller runs last, and only for requests that pass the filters.
  • Validation: Incorrect. Validating first would give unauthorized callers feedback about the body.