Cheatsheet

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.

Structure (UML)

Spring contextAuditRule30MembershipRuleWaiverRule×10CapacityRule«i»AccessRuleCheckInControllerAccessControlAthlete

Participants

  • Handler (AccessRule, or AccessHandler in the hand-written version), the contract for every link
  • ConcreteHandler (MembershipRule, WaiverRule, CapacityRule, AuditRule), each with a single check
  • The chain (AccessChain), which carries the request from one link to the next
  • Client (AccessControl, called by the controller), which hands the request to the first link

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
    }
}

Pros

  • Each rule lives in its own class, small and easy to test
  • Adding or removing a rule doesn't touch the others (as long as it respects the order)
  • A link can act before and after the rest, like AuditRule

Cons

  • Order matters and must be set on purpose
  • You have to decide what happens if nobody says no; here the door opens by default, while Spring Security denies by default
  • Following a request through the chain is harder than reading one method full of ifs

← Chain of Responsibility · Run it