Skip to the content.

Chain of Responsibility

The problem

Before the shop accepts an order it must pass a series of checks: is everything in stock? is there a shipping address? does it look fraudulent? A single validateOrder method holding all the rules becomes a wall of ifs where the rules can’t be reordered, reused, or tested independently – and every new rule means editing (and re-risking) the same method.

The pattern

Each check is a self-contained handler; handlers are linked into a chain and each either rejects the request or passes it along:

OrderCheck validation = OrderCheck.chainOf(List.of(
        new StockCheck(inStock), new AddressCheck(), new FraudCheck()));
ValidationResult result = validation.validate(request);

This is the servlet-filter / middleware shape: the pipeline is configuration, the steps are components.

Benefits

Seen in the wild

Servlet Filter chains, Spring Security’s filter chain, Spring MVC interceptors, Netty’s ChannelPipeline, logging frameworks passing events up the logger hierarchy.

Implementation

Example test

OrderValidationChainTest