Part 5 of 6 · 3 min read
In practice
Checks, filters and middleware.
Validation chains and real systems
A common modern form is a list of checks. Each check looks at the request and either rejects it with a message or lets it pass to the next check.
record Request(String user, int hours, boolean paid) {}
interface Check { String apply(Request r); } // an error message, or null if fine
static String run(List<Check> chain, Request r) {
for (Check c : chain) {
String e = c.apply(r);
if (e != null) return e;
}
return "accepted";
}
With checks for "hours must be positive", "too long" for more than 8 hours, and "payment missing", a request with 0 hours is rejected first with "hours must be positive". A request with 3 hours and no payment gets "payment missing". A request with 3 hours and payment returns "accepted". The order of the list is the order of the chain, and a new rule is a new element.
This list form is the same idea without the successor links. It is shorter in Java, and easy to read, and it fits when every handler is simple. The linked form suits handlers that decide for themselves whether to pass the request on, or that act both before and after the rest of the chain.
Real systems use this idea often. Web servers pass each request through filters, such as authentication, logging and compression, before the real handler. Exception handling in a language passes an error up through callers until one catches it. A support system escalates a ticket from level 1 to level 2 to level 3.
Chain of Responsibility looks like Decorator, because both link objects in a line. A decorator always forwards the call and adds behaviour. A handler may decide to stop the request. It also looks like Command: a command is the request itself, and the chain is how a request finds its handler. The two can be combined.
Common mistake
Making every handler run for every request when you meant the first match only, or the reverse. Decide and write down whether the chain stops at the first handler that acts.
Interview angle
Answer in your head first, then open it.
What is the Chain of Responsibility pattern?
A request is passed along a line of handlers, and the first one able to handle it does, so the sender does not know the receiver.
What can go wrong?
The request may reach the end with no handler, so end with a default.
Where is it used?
Approval flows, support escalation, request filters in web servers and validation steps.
Check yourself: 1. How does a decorator differ from a handler in the chain? 2. Give two real systems that use a chain.
Words you will meet
| Word | Meaning |
|---|---|
| Handler | An object that may handle a request |
| Successor | The next handler in the chain |
| Chain | A line of handlers linked one after another |
| Escalation | Passing a request to a more senior handler |
| Filter | A step that can inspect or stop a request |