Notes
The problem
Here is the naive version. One method logs the request, checks for fraud, then walks through amount limits to decide who approves. Every rule, and the order of the rules, is welded into this method. Adding a festival season rule, or letting premium customers skip the agent, means editing it again. You cannot test one rule alone, and you cannot reuse the same rules in a different order for another country.
Decision decide(RefundRequest r) {
log(r);
if (r.refundsThisMonth() > 3)
return reject("too many");
if (r.amount() <= 500) return auto();
if (r.amount() <= 5000) return agent();
if (r.amount() <= 50000) return lead();
return escalate();
} // a new rule edits this method The idea
The idea in one sentence: link a set of handlers in a line and send the request to the first one. Each handler looks at the request and decides: deal with it, stop it, or pass it to the next handler. The sender does not know which handler will finally deal with it. And because the chain is assembled outside the handlers, you can reorder it, add to it or remove from it without touching any handler.
- link handlers in a line; send
- the request to the first; each
- one handles it, stops it, or
- passes it to the next
- the sender does not know which
- handler will deal with it
- the chain is built outside
- the handlers, so it can change
The structure
The participants. RefundDesk is the client. It builds the chain and sends each refund request to the first handler. RefundHandler is the abstract handler: it holds a reference to the next handler and a helper to pass the request on. The concrete handlers are AuditTrail, FraudScreen, AutoApprover, SupportAgent and FinanceLead. RefundRequest is a simple record with the order, the amount and how many refunds the customer had this month.
The code: base class
The base class has three parts. A private next field. A method called then, which sets the next handler and returns it, so the chain can be built in one readable line. And a protected pass on method that forwards to the next handler, or, at the end of the chain, returns an unhandled decision. That last part matters: a request must never silently fall off the end of the chain.
abstract class RefundHandler {
private RefundHandler next;
RefundHandler then(RefundHandler n) {
next = n; return n; }
abstract Decision handle(RefundRequest r);
Decision passOn(RefundRequest r) {
return next == null
? Decision.unhandled()
: next.handle(r);
}
} The code: handlers
Each concrete handler is small and checks one thing. The fraud screen rejects the request if the customer already had more than three refunds this month, and otherwise passes it on. The auto approver approves anything up to five hundred, and otherwise passes it on. The support agent and finance lead look the same with bigger limits. Each handler can be tested alone, by giving it a request and checking the decision.
class FraudScreen extends RefundHandler {
Decision handle(RefundRequest r) {
if (r.refundsThisMonth() > 3)
return Decision.rejected(...);
return passOn(r); } }
class AutoApprover extends RefundHandler {
Decision handle(RefundRequest r) {
if (r.amount() <= 500)
return Decision.approved("auto");
return passOn(r); } } Run-through
Let us follow a refund of three thousand two hundred. The desk sends it to the audit trail, which logs it and passes it on. The fraud screen sees only one earlier refund this month, so it passes it on. The auto approver sees it is over five hundred and passes it on. The support agent's limit is five thousand, so the agent approves it and returns the decision. The finance lead never sees it. The desk only ever talked to the first handler.
Two styles
There are two flavours of this pattern. In the first, exactly one handler deals with the request, and the rest never see it. Our approval levels work like that, and so does an exception travelling up the call stack until a matching catch block handles it. In the second flavour, a pipeline, every handler does its part and passes it on, but any handler may stop early. Web middleware works like that: logging, authentication, rate limiting, then validation. Our chain mixes both.
- first one wins:
- approvals, event bubbling,
- catch blocks up a call stack
- exactly one handler decides
- pipeline (middleware):
- every handler does its part
- and any one may stop early
- logging, auth, rate limits,
- validation, compression
Ends, order, loops
Three things to get right. First, the end of the chain. Decide what happens when nobody handles the request: return an unhandled result, escalate to a person, or put a catch all handler at the end. Never return null. Second, order matters. Put cheap and strict checks first, so fraud is screened before anything is approved. Treat the order as configuration. Third, never let the chain point back to itself, and keep it short, because a long chain is hard to debug.
- the end: return unhandled,
- escalate, or a default
- handler; never return null
- order matters: cheap and
- strict checks first (fraud
- before approval)
- no loops: a chain that points
- back to itself never ends
- keep chains short: long ones
- are hard to debug
When to use it
Use the pattern when several objects might handle a request and the sender should not choose between them, or when the handlers and their order change by configuration, customer type or country. Skip it when there are two fixed rules, because a plain if else is clearer. Be careful when every request must be handled, since a chain can let a request slip through. And remember that stepping through a long chain in a debugger is slower than reading one method.
- use it when:
- several objects may handle a
- request and you do not want
- the sender to pick one
- the handlers or their order
- change by config or country
- skip it when:
- two fixed rules: if-else is
- clearer
- every request must be handled
vs its neighbours
How does it differ from its neighbours? A decorator wraps one object, and every layer runs and adds behaviour. It normally does not stop the call. Observer tells every listener about an event, in no promised order, and no listener can stop the others. A chain is ordered, and one handler decides, or any handler may stop the request. Middleware sits between chain and decorator, which is why the two are often confused.
- Decorator: wraps one object,
- every layer runs and adds
- behaviour, never stops it
- Observer: every listener
- hears the event, no order,
- none can stop the others
- Chain: ordered handlers, one
- decides or any may stop
In Java
Java web code is full of this pattern. A servlet filter receives the request, the response and a filter chain object. It can stop the request, for example when the user is not authorised, or call do filter on the chain to pass it to the next filter and finally to the servlet. Spring Security is built as a chain of such filters. And in java dot util dot logging, a logger hands each log record to its parent logger's handlers too, unless you turn that off.
// a servlet filter
public void doFilter(ServletRequest req,
ServletResponse res,
FilterChain chain) ... {
if (!authorised(req)) { deny(res);
return; } // stop here
chain.doFilter(req, res); // pass on
}
// also: Spring Security filter chain,
// java.util.logging parent handlers In LLD interviews
In machine coding rounds, listen for levels, escalation, approvals or middleware. A logger can route messages through handlers for each level. An A T M dispenser is a favourite: the two thousand note handler takes what it can and passes the rest to the five hundred handler, then to the one hundred handler. Leave and expense approvals, support ticket escalation and an A P I gateway with authentication, rate limiting and validation all fit naturally.
- logger: handlers per level,
- each decides to write or not
- ATM: note dispensers 2000,
- 500, 100 each take a share
- and pass the rest on
- leave or expense approvals
- API gateway: auth, rate limit,
- validation as middleware
- support ticket escalation
- vending machine coin checks
Mistakes to avoid
Common mistakes. A request that falls off the end of the chain with no answer. A handler that forgets to pass the request on and silently swallows it, which the template style base class helps prevent. Handlers that refer to each other by concrete class, so the chain cannot be rebuilt. An order that approves before checking for fraud. And a chain that accidentally loops back to an earlier handler. Mention each of these and you show real experience.
- request falls off the end
- with no answer
- handler forgets to call next
- and silently swallows it
- handlers know each other
- by concrete class
- wrong order: approve before
- the fraud check
- a loop in the chain