Published
- 8 min read
Chain of Responsibility in Java: Three Checks, Any of Them Can Stop It
One class per check, each one stopping the order or passing it on: by hand, in the filter chain every Spring request runs through, and as beans in the order you set.
Your interviewer asks: before an order is paid, it has to pass three checks, fraud, stock and coupon, and any of them can stop it. Is that the Observer pattern?
If you said yes, that’s the trap. An observer only gets told what happened, so it can’t say no. Checks that stand in the order’s way, one after another, where each one can stop it or pass it on, are a Chain of Responsibility. It is the question the Observer pattern post ended on.
The version with an if for every check
Most of us write it like this, one method with an if for every check:
void validate(Order o) {
if (o.risky()) {
throw new Rejected("fraud");
}
if (!o.inStock()) {
throw new Rejected("stock");
}
if (!o.couponValid()) {
throw new Rejected("coupon");
}
}
That’s fine until the risk team wants a spending limit, and you are back in that method:
void validate(Order o) {
// fraud, stock, coupon: the same
if (o.total() > LIMIT) {
throw new Rejected("limit");
}
}
Every new rule is another edit to the same method, and another reason to retest every rule in it. The rules can’t be reordered, switched off for one kind of order, or tested on their own.
Chain of Responsibility
Chain of Responsibility gives every check its own class, behind one interface:
interface Check {
void check(Order o, Chain next);
}
Each check either stops the order or passes it on to the next:
class FraudCheck implements Check {
public void check(Order o,
Chain next) {
if (o.risky()) {
throw new Rejected("fraud");
}
next.proceed(o);
}
}
None of them knows what comes after it. A check holds a Chain, not the next check, and the chain hands the order
to whichever check is next in its list:
class Chain {
final Iterator<Check> rest;
Chain(Iterator<Check> rest) {
this.rest = rest;
}
void proceed(Order o) {
if (rest.hasNext()) {
rest.next().check(o, this);
}
}
}
So you can add, drop or reorder checks without touching the rest. The spending limit is one more class, and the method that runs the checks doesn’t change:
@Component
class LimitCheck implements Check {
public void check(Order o,
Chain next) {
if (o.total() > LIMIT) {
throw new Rejected("limit");
}
next.proceed(o);
}
}
/CodeVxDev
chain
java ChainOfResponsibility.java
14:36:41
The textbook calls each check a handler and the request is whatever travels down the line: here an order, in a web app an HTTP request.
Not Observer, and not State either
Three behavioral patterns get mixed up here, because in all three an object hands work to others. What separates them is who decides what happens next:
| Chain of Responsibility | Observer | State | |
|---|---|---|---|
| Can it say no? | Yes: a handler stops the request | No: a listener is told after the fact | It refuses what its state doesn’t allow |
| Who picks the next step | The chain; a handler never knows it | Nobody: every listener gets the event | Each state returns the next one |
| Lifetime | One request, start to finish | One event, many listeners | One object, its whole life |
| Adding one | A new class (LimitCheck), no edits | A new listener, no edits | A new state, plus the one that leads to it |
The last row is the one that shows in code. In the State pattern post, adding the
out-of-cash state meant a new NoCash class and a line in HasPin, because a state names its successor. Here,
LimitCheck edits nothing: a check never learns who comes after it.
Observer has one catch worth knowing for the interview. A synchronous Spring listener that throws does fail the payment (the Observer post shows it), but that is an accident of running in the same thread. No listener can say no on purpose, and nobody promises the order in which listeners run.
You already rely on it: the filter chain
Every request to a Spring web app runs through a filter chain. A servlet filter has the same shape as a check:
public void doFilter(
ServletRequest req,
ServletResponse res,
FilterChain chain) {
if (!hasToken(req)) {
reject(res);
return;
}
chain.doFilter(req, res);
}
If there is no token, the filter answers the request itself and returns: nothing after it runs, not even your
controller. Otherwise it calls chain.doFilter to pass it along. The real method also declares
throws IOException, ServletException; hasToken and reject are our helpers.
Spring Security is this pattern at scale. Its SecurityFilterChain is an ordered list of filters (CORS, CSRF,
authentication, authorization and more), and each one can end the request with a 401 or 403. When you write
your own filter, extend OncePerRequestFilter: it runs once per request even when the request is forwarded
internally, and its doFilterInternal gets the same FilterChain to pass the request on.
In Spring: a List of beans, in the order you set
For your own checks, let Spring build the chain. Make each check a bean, ask for a List of them, and Spring hands
them over:
@Service
@RequiredArgsConstructor
class Checkout {
private final List<Check> checks;
void validate(Order o) {
new Chain(checks.iterator())
.proceed(o);
}
}
Lombok’s @RequiredArgsConstructor writes the constructor Spring injects through. A spending limit? One more
check: LimitCheck above is a @Component, so Spring finds it and adds it to the list. Checkout doesn’t change.
The list comes in the order you set, and only if you set one. Spring sorts a List of beans by @Order (or the
Ordered interface); beans without either come last, in registration order, which depends on class scanning and
which nobody should rely on. In a chain the order matters: put the cheap checks first, and the ones that call
another service last.
One snag in this example: the annotation is called Order and so is the domain class. Two types with the same
simple name can’t both be imported, so write the annotation out in full:
@Component
@org.springframework.core.annotation.Order(1)
class FraudCheck implements Check { ... }
Before you ship it
The bug the pattern invites
A check that forgets next.proceed(o) doesn’t fail. The checks after it never run, and the order goes through
unchecked. Here an audit check that only logs the order, placed before the stock check, forgets the call:
/CodeVxDev
chain
java ForgotNext.java
14:36:41
An out-of-stock order got paid, and nothing in the log says a check was skipped. A servlet filter that forgets
chain.doFilter does the same to a web request: the controller never runs, and the client gets an empty 200 response.
Two shapes of the pattern
There are two ways to build a chain, and the bug above is the reason to know both:
- Each handler calls the next (servlet filters, the code above). A handler can do work after the rest of the chain has run, which is how a filter times a request or cleans up after it. The price is that one forgotten call silently skips everything after it.
- A runner loops over the handlers (the second half of the output above). Each check returns or throws, and the loop moves on, so no check can skip the others. Most validation chains want this shape:
for (Rule rule : rules) {
rule.check(o); // throws to stop
}
And the rest
- Stopping by exception or by result. Throwing is simple, but a rejected order isn’t exceptional. A check that
returns
Optional<Rejection>or a small result type lets the caller collect every reason, not only the first. - Order is a contract. Write a test that the list arrives in the order you meant, so a new
@Ordervalue can’t slip a slow check in front of a cheap one. - Keep checks independent. A check that relies on another one having run first is a hidden dependency that the next reorder will break.
Spot it in LLD interviews
When one request goes down a line of handlers and any of them can stop it, think Chain of Responsibility:
| LLD question | The request | The handlers, in order |
|---|---|---|
| Checkout validation | An order | Fraud, stock, coupon, spending limit |
| ATM cash dispenser | An amount | 100, 50 and 20 note dispensers |
| Expense approval | An expense claim | Manager, director, CFO (by amount) |
| Support desk | A ticket | Level 1, level 2, level 3 |
| Spam filter | An email | Blocklist, link scan, content |
| API gateway | An HTTP request | Auth, rate limit, validation, routing |
| Logging framework | A log record | Console, file, alerting (by level) |
The ATM dispenser is worth a sentence in the interview, because the same machine was the State pattern in the State pattern post: its steps (idle, card inserted, PIN entered) are State, and the dispenser that splits an amount into notes, each handler taking what it can and passing on the rest, is a chain. In the interview, name the request first, then show the handler interface and how a new handler joins the line without touching the others.
When not to use it
If every step always runs and nothing can stop the request, it’s a pipeline, not a chain: a list of functions is enough. And if there are only two fixed rules that never change, the if-else is easier to read.
/CodeVxDev
chain
cat chain.md
14:36:41
The interview trap
You wrap a payment client in a logger, then wrap that in a retry, and each one calls the next. Is that another chain?
A. Another chain   B. Not a chain
Think about what a handler in a chain is allowed to do that a wrapper never does. Leave A or B as a
comment on the video; the next episode in this series answers it.