Expense approval chain
An expense travels through links – receipt check, team lead, manager, director – until someone approves or rejects it. Chain of Responsibility with pluggable links.
In the company's expense app the amount decides who approves: a team lead up to 1,000, a manager up to 5,000, a director up to 20,000. Before that, every expense above 50 must have a receipt. The rules keep changing (finance wants a fraud check next), so instead of one huge if we build a Chain of Responsibility: every link either handles the expense or passes it on.
Task
ApprovalHandler(in Go – the embeddedLinkstruct):setNext(handler)links the next handler and returns it, so the chain can be built fluently:a.setNext(b).setNext(c);- the default
handle(expense)passes the expense on and, at the end of the chain, returnsrejected: no approver.
ReceiptCheck– an expense above 50 without a receipt ends withrejected by receipt-check; anything else goes on.Approver(name, limit)– approves an amount not greater thanlimit(approved by <name>) and passes bigger ones on.defaultChain()– the chainreceipt-check → team-lead (1,000) → manager (5,000) → director (20,000).
| Expense | Result |
|---|---|
| 300, with a receipt | approved by team-lead |
| 1,001, with a receipt | approved by manager |
| 120, no receipt | rejected by receipt-check |
| 25,000 | rejected: no approver |
The tests add their own links (a fraud check and a recorder) – they must work without changing the existing classes. Names per language: set_next/default_chain (Python), SetNext/ExpenseApproval.DefaultChain() (C#), ExpenseApproval.defaultChain() (Java), SetNext/PassOn/DefaultChain() (Go).
Topics: Chain of Responsibility
Related articles
- 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,…