Published on

Design Pattern: Chain of Responsibility - The Butterfly Effect

Authors

Chain of Responsibility (CoR) is a Behavioral Pattern in common Design Patterns. CoR embodies the idea of breaking down processing into a chain of smaller processes, where each Node within the chain takes on a specific role and passes its output to the next Node.

Real-World Problem: Order Validation

Consider the process of handling an order in an e-commerce application. There are several steps that need to be performed:

  • Is the user authenticated?
  • Does the user have sufficient privileges?
  • Has the user paid?
  • Is the data in the request valid?
  • Is there a cached response for this request?
  • Finally, process the order.

Without CoR, you might implement the feature with a long and complex function, checking each condition one by one.

Adding new checks or changing the order becomes a major challenge.

Solution With CoR: Create a Processing Chain

The Chain of Responsibility Pattern proposes creating a chain of object handlers. Each handler is responsible for a specific part of the processing. When a request arrives, it is "passed" to the first handler in the chain.

Each handler then decides:

  • Can I handle this request? If so, the handler performs its job.
  • Should I pass it on? The handler can process part of the request and then pass it on to the next handler for further processing, or it can decide to stop the chain if it has finished processing the request (or if a check fails).

!!! Fun Tip: Reactive Programming is a form of Chain of Responsibility

When to Use Chain of Responsibility

CoR is very versatile, you can apply it anywhere in any type of project, not necessarily Backend or Frontend, etc.

When analyzing a problem, proposing a solution, you need to break down the solution into multiple steps, each with a specific role. After breaking it down, all that remains is to apply CoR to implement it in code.

Chain of Responsibility helps us have source code that is neat, powerful, very easy to test with Unit Tests, and also easy to replace and maintain when requirements change.

Follow my Youtube and Facebook channels to update more knowledge!

@dantech