Chain of Responsibility Pattern
Some requests can be dealt with by more than one object, and which one depends on the request itself. An expense of $300 is approved by your manager, $8,000 needs a director, and $40,000 goes to the CFO. A web request has to pass a login check, a rate limit and input validation before it reaches the code that does the real work, and any of those checks may turn it away.
The Chain of Responsibility pattern lines the handlers up and passes the request from one to the next. Each handler decides for itself: deal with the request, pass it along, or stop it. The code that sends the request only knows the first handler in the line.
🔗 In one sentence: put each step that might handle a request in its own handler object, link the handlers into a chain, and let each one either handle the request or hand it to the next, so you can add, remove or reorder steps without touching the sender or the other steps.
The Problem It Solves
Here is expense approval written the way it usually starts: one method, one branch per approval level.
class ExpenseService:
def approve(self, expense: Expense) -> str:
if expense.amount <= 0:
return "rejected: invalid amount"
if expense.amount <= 1_000:
return "approved by manager"
elif expense.amount <= 10_000:
if expense.category == "travel" and expense.amount <= 5_000:
return "approved by manager" # travel exception
if expense.department == "engineering":
return "approved by CFO" # engineering has no director
return "approved by director"
elif expense.amount <= 50_000:
return "approved by CFO"
else:
return "rejected: needs board review"
It reads fine today. The trouble is in what happens next.
The rules and the order are welded together. Each level is a branch, and the branches only make sense in this order because each one assumes the earlier ones already failed. Adding a VP between director and CFO means editing the ranges of the branches on either side and re-checking every boundary.
Every department gets a variation of the same chain. Engineering skips the director, so a special case sits
inside the director branch. When a second department wants its own path, the method grows another if on
department, and the shape of each chain is hidden in the nesting.
Rules for one level leak into another. The travel exception is a manager rule, but it lives in the director branch, because that is where the code happened to be when the rule arrived.
One level is hard to test. To test the director limit, you build expenses that carefully avoid every branch above it. A test for one rule depends on all of them.
⚠️ The smell to look for: a long
if/elifwhere each branch means "if I can deal with this, do it; otherwise fall through to the next one", or a request handler that starts with five unrelated checks before the real work. Both are chains written as one function.