7
Back to Boss Battles

Chain of ResponsibilityVSDecorator

The Problem

Scenario A β€” Chain of Responsibility territory: Your document approval workflow goes through team lead, manager, then compliance. Each can approve, reject (stopping the chain), or escalate. If the amount is under $100, the team lead approves directly without passing further.

Scenario B β€” Decorator territory: Your HTTP response pipeline adds gzip compression, CORS headers, and cache-control headers. Every response goes through all three steps β€” none can short-circuit. Each adds something and passes the response along.


Why They Look Alike

Both create a chain of objects where each links to the next. Both use the same interface. Both process a request sequentially. The wiring code looks identical: A β†’ B β†’ C.

Rendering diagram…

The Core Difference

AspectChain of ResponsibilityDecorator
Can stop earlyYes β€” a handler can reject/handle without passing onNo β€” always delegates to the wrapped object
PurposeFind the right handler or filterAdd behavior on top of existing behavior
Request flowMay stop at any linkAlways flows through all wrappers
Handler knows next?Optionally (can end the chain)Always wraps exactly one object
Return valueHandler's result OR next handler's resultEnhanced result of the wrapped object
AnalogySupport ticket escalation β€” someone handles itGift wrapping β€” each layer adds wrapping paper
Real-worldExpress middleware, NestJS guards, approval pipelinesLogging decorator, caching decorator, compression

One sentence: CoR can short-circuit (someone handles it and stops); Decorator always passes through (everyone adds their layer).


Side-by-Side Code

Chain of Responsibility β€” Approval pipeline

typescript
1interface ApprovalHandler {
2 setNext(handler: ApprovalHandler): ApprovalHandler;
3 approve(request: PurchaseRequest): ApprovalResult;
4}
5
6abstract class BaseApprovalHandler implements ApprovalHandler {
7 private next: ApprovalHandler | null = null;
8
9 setNext(handler: ApprovalHandler): ApprovalHandler {
10 this.next = handler;
11 return handler;
12 }
13
14 approve(request: PurchaseRequest): ApprovalResult {
15 if (this.next) return this.next.approve(request);
16 return { approved: false, reason: 'No handler could approve' };
17 }
18}
19
20class TeamLeadApprover extends BaseApprovalHandler {
21 approve(request: PurchaseRequest): ApprovalResult {
22 if (request.amount < 100) {
23 return { approved: true, approver: 'Team Lead' }; // STOPS here
24 }
25 return super.approve(request); // pass to next
26 }
27}
28
29class ManagerApprover extends BaseApprovalHandler {
30 approve(request: PurchaseRequest): ApprovalResult {
31 if (request.amount < 1000) {
32 return { approved: true, approver: 'Manager' }; // STOPS here
33 }
34 return super.approve(request);
35 }
36}
37
38// Chain: teamLead β†’ manager β†’ director
39const teamLead = new TeamLeadApprover();
40teamLead.setNext(new ManagerApprover()).setNext(new DirectorApprover());
41teamLead.approve({ amount: 50 }); // handled by TeamLead, stops
42teamLead.approve({ amount: 500 }); // passed to Manager, stops

Decorator β€” Response enhancement

typescript
1interface ResponseHandler {
2 handle(req: Request): Promise<Response>;
3}
4
5class CoreHandler implements ResponseHandler {
6 async handle(req: Request): Promise<Response> {
7 return { status: 200, body: await this.fetchData(req), headers: {} };
8 }
9}
10
11class CorsDecorator implements ResponseHandler {
12 constructor(private wrapped: ResponseHandler) {}
13
14 async handle(req: Request): Promise<Response> {
15 const res = await this.wrapped.handle(req); // ALWAYS delegates
16 res.headers['Access-Control-Allow-Origin'] = '*';
17 return res; // adds CORS, passes everything through
18 }
19}
20
21class CompressionDecorator implements ResponseHandler {
22 constructor(private wrapped: ResponseHandler) {}
23
24 async handle(req: Request): Promise<Response> {
25 const res = await this.wrapped.handle(req); // ALWAYS delegates
26 res.body = gzip(res.body);
27 res.headers['Content-Encoding'] = 'gzip';
28 return res; // adds compression, passes everything through
29 }
30}
31
32// Every decorator runs β€” no short-circuiting
33const handler = new CompressionDecorator(
34 new CorsDecorator(
35 new CoreHandler()
36 )
37);

Decision Rules

SignalChooseWhy
A handler may stop the chain (reject, handle completely)CoRShort-circuit capability
Every step must run (adds behavior, never skips)DecoratorAlways delegates through
Finding the right handler for a requestCoRFirst match handles it
Stacking enhancements on an objectDecoratorEach wrapper adds a layer
Express middleware (next() is optional)CoRMiddleware can end the response
Logging/caching/compression wrappersDecoratorAlways pass through
Auth guards (deny = stop, allow = continue)CoRCan short-circuit on denial

The Trick Question

"Your NestJS middleware pipeline: auth checks β†’ rate limiting β†’ request logging β†’ route handler. Auth and rate limiting can reject. Logging always passes through. Which pattern?"

This is Chain of Responsibility overall β€” because auth and rate limiting can short-circuit (return 401 or 429 without calling next()). The fact that logging always passes through doesn't make it a Decorator; in CoR, some handlers choose to always pass, some choose to stop. The capability to stop is what defines CoR.

If NONE of the handlers could ever stop β€” all always pass through β€” then it would be Decorator.


Interview Angles

Q: Can you mix both in one pipeline? Yes. Express middleware is CoR (any middleware can end the response), but you might use Decorator within a single middleware to wrap the response object with additional behavior. The pipeline is CoR; individual enhancements are Decorator.

Q: How does NestJS organize these? Guards = CoR (can reject). Interceptors = Decorator-like (wrap execution, always continue). Pipes = CoR (can throw validation error). Middleware = CoR (can skip next()). The framework uses both patterns for different purposes.

Q: What about error handling middleware? Error handling middleware in Express ((err, req, res, next)) is CoR. Each error handler decides: handle the error and respond, or pass to the next error handler. The first one that matches handles it.

Q: Performance difference? Minimal. Both are O(n) through the chain. CoR may be faster on average because it short-circuits. Decorator always runs all layers. The difference only matters with very long chains.