1. The Problem: The Large Validation Method
Imagine a login request that needs to pass through:
- Auth Check (Is the user in the DB?)
- Rate Limit Check (Has the user tried 10 times in 1 min?)
- Role Check (Is the user an Admin?)
- Logging (Record the attempt).
If you put this all in one method, it becomes a "Monster Method" that is impossible to unit test and modify.
2. The Solution: Chain of Responsibility
We break each check into a separate Handler class. Each handler has a reference to the Next handler in the chain.
Step 1: The Handler Base
public abstract class Handler {
private Handler next;
public void setNext(Handler next) { this.next = next; }
public void handle(Request req) {
if (process(req) && next != null) {
next.handle(req);
}
}
protected abstract boolean process(Request req);
}
Step 2: Concrete Handlers
public class AuthHandler extends Handler {
protected boolean process(Request req) {
// Logic...
return true; // Pass to next
}
}
3. Real-world Intuition: The Support Call
- Level 1: Basic reset password? (Handled).
- Level 2: Bug in the app? (Forwarded to Level 2).
- Level 3: Server down? (Forwarded to Level 3).
4. Interview Discussion
- Pros: Follows SRP and OCP. You can add or reorder handlers without changing client code.
- Cons: A request might reach the end of the chain without being handled (always have a "Default Handler").
Final Takeaway
The Chain of Responsibility is about Pipeline Processing. Use it when you have a sequence of logic that could vary in order or complexity.