Article · Chain of Responsibility
Chain of Responsibility: pass it on until someone takes care of it
The Chain of Responsibility pattern through complaints in a pierogi place: a bot, a shift manager and the owner form a chain, and a complaint travels until it reaches someone authorised. The classic variant and the middleware pipeline, code in five languages.
A customer writes that the pierogi arrived cold. If it is about 15 PLN and there is a photo, a bot can issue the refund. For a larger amount the shift manager decides, and for a really big one – Halina herself. Chain of Responsibility lines such handlers up: a request travels from one to the next until someone takes it over.
- 3
- links in the chain – bot, shift manager, owner
- 20 PLN
- automatic refund limit – with a photo
- 1
- entry point for the sender – the first link
The problem: one function knows the whole hierarchy
Complaint handling started with an ordinary if/elif:
def handle_complaint(c: Complaint) -> str:
if c.amount <= 20 and c.has_photo:
return refund_automatically(c)
elif c.amount <= 100 and is_shift_manager_on_duty():
return ask_shift_manager(c)
elif c.amount <= 100:
return ask_owner(c) # copy of the branch below, "temporarily"
else:
return ask_owner(c)
# next request: "add an AI triage step before the bot, but only on weekends"The function knows all the participants of the process, their limits and their order. Every change – a new verification step, a different threshold, triage by an AI model at weekends – means editing the same function. Nor can you assemble a different chain for a different channel (complaints from the delivery app skip the bot, say) without copying the whole thing.
The solution: handlers linked into a chain
Every participant of the process becomes an object with a handle(complaint) method and a reference to the next link. A link checks whether it can handle the request; if so, it handles it and stops; if not, it passes it on. The order and composition of the chain are set by configuration code, not by the handlers themselves.
| Role | In the example | Responsibility |
|---|---|---|
| Handler | ComplaintHandler | the common interface and a reference to the next link |
| Concrete handler | AutoRefund, ShiftManager, Owner | decides: handle or pass on |
| Client | the complaint form | sends the request to the first link |
| Configuration | the code building the chain | sets the composition and order of links |
Implementation in five languages
In C#, TypeScript, Java and Python the base class holds a reference to the next link and implements the "handle or pass on" logic, while subclasses only provide the condition and the way to handle it. setNext returns the next link, so the chain is built fluently. In Go a link is a struct with two functions, and the Chain function assembles the chain.
Chain of Responsibility – complaints
var chain = new AutoRefund();
chain.SetNext(new ShiftManager()).SetNext(new Owner());
Console.WriteLine(chain.Handle(new Complaint(101, 15m, HasPhoto: true))); // Bot: refunded 15 PLN
Console.WriteLine(chain.Handle(new Complaint(102, 15m, HasPhoto: false))); // Shift manager approved 15 PLN
Console.WriteLine(chain.Handle(new Complaint(103, 340m, HasPhoto: true))); // Halina will call the customer
public sealed record Complaint(int OrderId, decimal Amount, bool HasPhoto);
public abstract class ComplaintHandler
{
private ComplaintHandler? _next;
// Returns the next handler, so the chain can be built fluently.
public ComplaintHandler SetNext(ComplaintHandler next) => _next = next;
public string Handle(Complaint c) =>
CanHandle(c) ? Resolve(c)
: _next?.Handle(c) ?? $"#{c.OrderId}: nobody could handle the complaint";
protected abstract bool CanHandle(Complaint c);
protected abstract string Resolve(Complaint c);
}
public sealed class AutoRefund : ComplaintHandler
{
protected override bool CanHandle(Complaint c) => c.Amount <= 20m && c.HasPhoto;
protected override string Resolve(Complaint c) => $"#{c.OrderId}: Bot: refunded {c.Amount} PLN";
}
public sealed class ShiftManager : ComplaintHandler
{
protected override bool CanHandle(Complaint c) => c.Amount <= 100m;
protected override string Resolve(Complaint c) => $"#{c.OrderId}: Shift manager approved {c.Amount} PLN";
}
public sealed class Owner : ComplaintHandler
{
protected override bool CanHandle(Complaint c) => true; // the last link takes everything
protected override string Resolve(Complaint c) => $"#{c.OrderId}: Halina will call the customer";
}type Complaint = { orderId: number; amount: number; hasPhoto: boolean };
abstract class ComplaintHandler {
private next?: ComplaintHandler;
/** Returns the next handler, so the chain can be built fluently. */
setNext(next: ComplaintHandler): ComplaintHandler {
this.next = next;
return next;
}
handle(c: Complaint): string {
if (this.canHandle(c)) return this.resolve(c);
return this.next?.handle(c) ?? `#${c.orderId}: nobody could handle the complaint`;
}
protected abstract canHandle(c: Complaint): boolean;
protected abstract resolve(c: Complaint): string;
}
class AutoRefund extends ComplaintHandler {
protected canHandle(c: Complaint) { return c.amount <= 20 && c.hasPhoto; }
protected resolve(c: Complaint) { return `#${c.orderId}: Bot: refunded ${c.amount} PLN`; }
}
class ShiftManager extends ComplaintHandler {
protected canHandle(c: Complaint) { return c.amount <= 100; }
protected resolve(c: Complaint) { return `#${c.orderId}: Shift manager approved ${c.amount} PLN`; }
}
class Owner extends ComplaintHandler {
protected canHandle() { return true; } // the last link takes everything
protected resolve(c: Complaint) { return `#${c.orderId}: Halina will call the customer`; }
}
const chain = new AutoRefund();
chain.setNext(new ShiftManager()).setNext(new Owner());
console.log(chain.handle({ orderId: 101, amount: 15, hasPhoto: true })); // Bot: refunded 15 PLN
console.log(chain.handle({ orderId: 102, amount: 15, hasPhoto: false })); // Shift manager approved 15 PLN
console.log(chain.handle({ orderId: 103, amount: 340, hasPhoto: true })); // Halina will call the customerrecord Complaint(int orderId, double amount, boolean hasPhoto) {}
abstract class ComplaintHandler {
private ComplaintHandler next;
// Returns the next handler, so the chain can be built fluently.
ComplaintHandler setNext(ComplaintHandler next) {
this.next = next;
return next;
}
final String handle(Complaint c) {
if (canHandle(c)) return resolve(c);
return next != null ? next.handle(c) : "#" + c.orderId() + ": nobody could handle the complaint";
}
protected abstract boolean canHandle(Complaint c);
protected abstract String resolve(Complaint c);
}
class AutoRefund extends ComplaintHandler {
protected boolean canHandle(Complaint c) { return c.amount() <= 20 && c.hasPhoto(); }
protected String resolve(Complaint c) { return "#%d: Bot: refunded %.0f PLN".formatted(c.orderId(), c.amount()); }
}
class ShiftManager extends ComplaintHandler {
protected boolean canHandle(Complaint c) { return c.amount() <= 100; }
protected String resolve(Complaint c) { return "#%d: Shift manager approved %.0f PLN".formatted(c.orderId(), c.amount()); }
}
class Owner extends ComplaintHandler {
protected boolean canHandle(Complaint c) { return true; } // the last link takes everything
protected String resolve(Complaint c) { return "#%d: Halina will call the customer".formatted(c.orderId()); }
}
public class Complaints {
public static void main(String[] args) {
var chain = new AutoRefund();
chain.setNext(new ShiftManager()).setNext(new Owner());
System.out.println(chain.handle(new Complaint(101, 15, true))); // Bot: refunded 15 PLN
System.out.println(chain.handle(new Complaint(102, 15, false))); // Shift manager approved 15 PLN
System.out.println(chain.handle(new Complaint(103, 340, true))); // Halina will call the customer
}
}package main
import "fmt"
type Complaint struct {
OrderID int
Amount float64
HasPhoto bool
}
type Handler interface {
Handle(c Complaint) string
}
// link is one handler in the chain: it resolves the complaint or passes it on.
type link struct {
name string
can func(Complaint) bool
resolve func(Complaint) string
next Handler
}
func (l *link) Handle(c Complaint) string {
if l.can(c) {
return fmt.Sprintf("#%d: %s: %s", c.OrderID, l.name, l.resolve(c))
}
if l.next == nil {
return fmt.Sprintf("#%d: nobody could handle the complaint", c.OrderID)
}
return l.next.Handle(c)
}
// Chain links the handlers in order and returns the first one.
func Chain(links ...*link) Handler {
for i := 0; i < len(links)-1; i++ {
links[i].next = links[i+1]
}
return links[0]
}
func main() {
chain := Chain(
&link{name: "Bot",
can: func(c Complaint) bool { return c.Amount <= 20 && c.HasPhoto },
resolve: func(c Complaint) string { return fmt.Sprintf("refunded %.0f PLN", c.Amount) }},
&link{name: "Shift manager",
can: func(c Complaint) bool { return c.Amount <= 100 },
resolve: func(c Complaint) string { return fmt.Sprintf("approved %.0f PLN", c.Amount) }},
&link{name: "Owner",
can: func(Complaint) bool { return true }, // the last link takes everything
resolve: func(Complaint) string { return "Halina will call the customer" }},
)
fmt.Println(chain.Handle(Complaint{101, 15, true}))
fmt.Println(chain.Handle(Complaint{102, 15, false}))
fmt.Println(chain.Handle(Complaint{103, 340, true}))
}from __future__ import annotations
from abc import ABC, abstractmethod
from dataclasses import dataclass
@dataclass(frozen=True)
class Complaint:
order_id: int
amount: float
has_photo: bool
class ComplaintHandler(ABC):
def __init__(self) -> None:
self._next: ComplaintHandler | None = None
def set_next(self, handler: ComplaintHandler) -> ComplaintHandler:
"""Returns the next handler, so the chain can be built fluently."""
self._next = handler
return handler
def handle(self, c: Complaint) -> str:
if self.can_handle(c):
return self.resolve(c)
if self._next is None:
return f"#{c.order_id}: nobody could handle the complaint"
return self._next.handle(c)
@abstractmethod
def can_handle(self, c: Complaint) -> bool: ...
@abstractmethod
def resolve(self, c: Complaint) -> str: ...
class AutoRefund(ComplaintHandler):
def can_handle(self, c): return c.amount <= 20 and c.has_photo
def resolve(self, c): return f"#{c.order_id}: Bot: refunded {c.amount:.0f} PLN"
class ShiftManager(ComplaintHandler):
def can_handle(self, c): return c.amount <= 100
def resolve(self, c): return f"#{c.order_id}: Shift manager approved {c.amount:.0f} PLN"
class Owner(ComplaintHandler):
def can_handle(self, c): return True # the last link takes everything
def resolve(self, c): return f"#{c.order_id}: Halina will call the customer"
chain = AutoRefund()
chain.set_next(ShiftManager()).set_next(Owner())
for complaint in (Complaint(101, 15, True), Complaint(102, 15, False), Complaint(103, 340, True)):
print(chain.handle(complaint))The rest of this article is for members
Create a free account or sign in to read it all. Still ahead:
- Step by step
- Different chains from the same links
- A variant: the middleware pipeline
- When to use it and when not to
- Related patterns
- In practice
- Test yourself