Chain of Responsibility

Intent
Pass a request along a chain of handlers; each one decides whether to handle it or let it through, without the sender knowing which one will answer.
Application
To get into class you need your membership paid, the waiver signed and a free spot. Turn every check into a link that decides or passes the turn, just like Spring Security's filters.
CheckInControllerMonolithicCheckInAthlete

The athlete sends Leo · 18:00 to CheckInController, which calls MonolithicCheckIn, highlighted in red.

The diagram doesn't change: MonolithicCheckIn stays highlighted in red as the method you'd have to open for every new rule.

Three handlers in a row, MembershipHandler, WaiverHandler and CapacityHandler, highlighted. Leo goes from the controller to the first and on to the second, which sends back denied.

The Spring context appears. AccessControl, highlighted together with the context, is wired to the row of rules: AuditRule, MembershipRule, WaiverRule and CapacityRule, all implementing AccessRule.

Ana · 18:00 travels from the athlete to the controller, decide() to AccessControl, and proceed() walks the whole row of rules, highlighted, all the way to CapacityRule; finally granted · 200 travels back from AccessControl to the controller.

Leo gets past MembershipRule; WaiverRule, highlighted, sends waiver not signed back and the chain stops before CapacityRule.

CapacityRule appears highlighted at the end of the row: it's the one that books the spot.

AccessControl sends proceed() to AuditRule, highlighted, and the granted answer comes back along the same link at the end.

Inside the Spring context, the GET /api/wods request reaches WaiverHeaderFilter, highlighted, which passes it on with doFilter() to DispatcherServlet.

Final view: the athlete, the controller, AccessControl and the row of rules implementing AccessRule, all inside the Spring context.

Step 1 of 10

The box door

It's 18:00 and Leo taps his card to get into class. Before opening, the door checks three things:

  1. His membership is paid.
  2. He has signed the waiver, the liability release form.
  3. There's a spot left in the class, and if so, it books it for him.

The first version puts everything in MonolithicCheckIn.checkIn(): a row of ifs that return "no" or, if you reach the end, "yes".

Step 2 of 10

One more rule

Tomorrow another one arrives: minors need a guardian's consent. You have to open the method, find the right place among the other ifs and hope you don't break anything. And at some point someone will put a check after booking the spot, and that spot will stay taken even though the athlete was rejected.

Step 3 of 10

Each rule, one link

Chain of Responsibility splits the method into links. Each handler checks one thing only and:

  • if it has the answer (a "no"), it returns it and the chain stops;
  • if not, it hands the check-in to the next one.

In the classic version, each AccessHandler keeps a reference to its next and the chain is assembled by hand: membership.linkWith(waiver).linkWith(capacity). Leo is stopped by WaiverHandler and the capacity one never hears about it.

In classic GoF, a single handler takes care of the request and the chain ends there. In the Spring version coming next (the filter-chain one), each link can also act and carry on, as you'll see with CapacityRule and AuditRule.

Step 4 of 10

Rules are beans

In Spring, each rule is a bean implementing AccessRule, with an @Order that sets its place. AccessControl gets the sorted list and, for every check-in, starts an AccessChain that walks it:

  • If there are no rules left, the athlete gets in.
  • If there are, it calls the next one passing the rest of the chain, and it's the rule that decides whether to call proceed() to carry on. It may do so once at most; a second call is an error.

It's the same shape as the servlet FilterChain.

Step 5 of 10

Ana gets in

Ana's membership is paid, her waiver is signed and there's a spot left:

  1. POST /api/check-ins?athlete=Ana&session=1 reaches AccessControl.
  2. Each rule checks its own thing and calls chain.proceed().
  3. CapacityRule books her a spot and, with no rules left, the chain answers granted: 200. If no rule says no, the door opens.

Look at MembershipRule: it either returns a "no" and cuts things short, or passes the turn. It doesn't know what comes next.

Step 6 of 10

Leo stays outside

Leo's membership is paid, but he has not signed the waiver:

  1. MembershipRule lets him through.
  2. WaiverRule answers denied("waiver not signed") and does not call proceed().
  3. The answer travels back through the chain: 403 with the reason.

CapacityRule never runs, so Leo doesn't use up a spot: there are still 2 left. The example test checks it.

Step 7 of 10

Order is part of the rule

CapacityRule is the only rule with an effect: it takes a spot, and as written it takes it before calling proceed(). That's why it goes last (@Order(30)). If it came before the waiver check, Leo would take a spot and then be turned away. Another option would be to call proceed() first and book only if the answer is granted; then its position wouldn't matter.

Step 8 of 10

Before and after

AuditRule goes first (@Order(0)) and does something curious: it calls chain.proceed() before doing anything. The whole rest of the chain runs "inside" that call, and when it returns, AuditRule sees the final answer and writes it to the log: "Ana → session 1: granted", "Leo → session 1: denied (waiver not signed)".

Step 9 of 10

Spring already does it for you

In a Spring MVC (servlet) app, every HTTP request goes through a servlet filter chain before reaching the DispatcherServlet. Spring Security joins that chain as a single filter (DelegatingFilterProxy, which delegates to FilterChainProxy), which in turn runs the filters of its SecurityFilterChain: authentication, CSRF, session, authorisation… Each one decides whether to cut the request short or call chain.doFilter().

The example test sets up a WaiverHeaderFilter. Without the X-Waiver-Signed header it answers 403 and the app never knows; with it, it calls chain.doFilter() and the request carries on.

Step 10 of 10

Recap

You started with a method full of ifs and ended up with:

  • One rule per class, with a single check.
  • @Order to set each one's place.
  • Cut or carry on: return an answer or call chain.proceed().
  • Links that wrap, like AuditRule, acting before and after the rest.

Cheatsheet →

Code

MonolithicCheckIn.java

public AccessDecision checkIn(CheckIn c) {
    if (!box.isActiveMember(c.athlete())) {
        return AccessDecision.deny("membership expired");
    }
    if (!box.hasSignedWaiver(c.athlete())) {
        return AccessDecision.deny("waiver not signed");
    }
    // new rule? open this method, find the right spot, hope you don't break the others
    if (!box.sessionExists(c.sessionId())) {
        return AccessDecision.deny("unknown session: " + c.sessionId());
    }
    if (!box.takeSpot(c.sessionId())) {
        return AccessDecision.deny("class is full");
    }
    return AccessDecision.allow();
}

MonolithicCheckIn.java

public AccessDecision checkIn(CheckIn c) {
    if (!box.isActiveMember(c.athlete())) {
        return AccessDecision.deny("membership expired");
    }
    if (!box.hasSignedWaiver(c.athlete())) {
        return AccessDecision.deny("waiver not signed");
    }
    // new rule? open this method, find the right spot, hope you don't break the others
    if (!box.sessionExists(c.sessionId())) {
        return AccessDecision.deny("unknown session: " + c.sessionId());
    }
    if (!box.takeSpot(c.sessionId())) {
        return AccessDecision.deny("class is full");
    }
    return AccessDecision.allow();
}

AccessHandler.java

public AccessHandler linkWith(AccessHandler next) {
    this.next = next;
    return next;                                   // lets you write a.linkWith(b).linkWith(c)
}

public AccessDecision handle(CheckIn checkIn) {
    AccessDecision mine = check(checkIn);
    if (mine != null) {
        return mine;                               // I answered: the chain stops here
    }
    return next == null ? AccessDecision.allow() : next.handle(checkIn);
}

/** Returns a decision to stop the chain, or null to let the next handler look. */
protected abstract AccessDecision check(CheckIn checkIn);

AccessChain.java

public AccessDecision proceed(CheckIn checkIn) {
    if (used) {
        throw new IllegalStateException("proceed() called more than once by the same rule");
    }
    used = true;
    if (index == rules.size()) {
        return AccessDecision.allow();                              // nobody objected: in you go
    }
    AccessRule next = rules.get(index);
    return next.check(checkIn, new AccessChain(rules, index + 1));  // it decides whether to go on
}

MembershipRule.java

@Component
@Order(10)
public class MembershipRule implements AccessRule {
    private final BoxRegistry box;

    public MembershipRule(BoxRegistry box) {
        this.box = box;
    }

    @Override
    public AccessDecision check(CheckIn checkIn, AccessChain chain) {
        if (!box.isKnown(checkIn.athlete())) {
            return AccessDecision.deny("unknown athlete");
        }
        if (!box.isActiveMember(checkIn.athlete())) {
            return AccessDecision.deny("membership expired");   // stop: the rest never runs
        }
        return chain.proceed(checkIn);                             // not my problem: next one
    }
}

AccessControlTest.java

AccessDecision decision = access.decide(new CheckIn("Leo", 1));

assertThat(decision).isEqualTo(AccessDecision.deny("waiver not signed"));
assertThat(box.spotsLeft(1)).isEqualTo(2); // the chain stopped before CapacityRule

CapacityRule.java

@Component
@Order(30)   // last on purpose: the only rule with a side effect (it takes a spot)
public class CapacityRule implements AccessRule {
    private final BoxRegistry box;

    public CapacityRule(BoxRegistry box) {
        this.box = box;
    }

    @Override
    public AccessDecision check(CheckIn checkIn, AccessChain chain) {
        if (!box.sessionExists(checkIn.sessionId())) {
            return AccessDecision.deny("unknown session: " + checkIn.sessionId());
        }
        if (!box.takeSpot(checkIn.sessionId())) {
            return AccessDecision.deny("class is full");
        }
        return chain.proceed(checkIn);
    }
}

AuditRule.java

@Component
@Order(0)
public class AuditRule implements AccessRule {
    /** Only the latest entries are kept, so a long-running door doesn't grow this forever. */
    public static final int KEEP = 100;

    private final Deque<String> log = new ArrayDeque<>();

    @Override
    public AccessDecision check(CheckIn checkIn, AccessChain chain) {
        AccessDecision decision = chain.proceed(checkIn);   // everything after me runs here...
        record(checkIn.athlete() + " → session " + checkIn.sessionId() + ": "
            + (decision.granted() ? "granted" : "denied (" + decision.reason() + ")"));
        return decision;                                    // ...and I see the answer on the way back
    }
    // …
}

SpringDoesItTooTest.java

static class WaiverHeaderFilter extends OncePerRequestFilter {
    @Override
    protected void doFilterInternal(HttpServletRequest req, HttpServletResponse res, FilterChain chain)
            throws ServletException, IOException {
        if (req.getHeader("X-Waiver-Signed") == null) {
            res.sendError(403, "waiver not signed");   // stop here: nobody further down sees it
            return;
        }
        chain.doFilter(req, res);                        // pass it along
    }
}

MembershipRule.java

@Component
@Order(10)
public class MembershipRule implements AccessRule {
    private final BoxRegistry box;

    public MembershipRule(BoxRegistry box) {
        this.box = box;
    }

    @Override
    public AccessDecision check(CheckIn checkIn, AccessChain chain) {
        if (!box.isKnown(checkIn.athlete())) {
            return AccessDecision.deny("unknown athlete");
        }
        if (!box.isActiveMember(checkIn.athlete())) {
            return AccessDecision.deny("membership expired");   // stop: the rest never runs
        }
        return chain.proceed(checkIn);                             // not my problem: next one
    }
}

Quiz

1. Leo hasn't signed the waiver. Which rules run when he checks in?

2. Why must CapacityRule be last?

3. AuditRule has @Order(0) and calls chain.proceed() before writing to its log. What does that achieve?

4. Where does Spring use this pattern most visibly?

Cheatsheet →

Run it