What is Chain Of Responsibility Pattern?

“With the Chain of Responsibility pattern, you can create a chain of objects that examine a request. Each object in turn examines the request and handles it, or passes it on to next object in the chain.” — Head First Design Patterns, Eric Freeman & Elisabeth Freeman

There are so many similar explanations out there most of them saying something like: “allows you to decouple the sender and the receiver of a request”.

In simple terms, when you have a list of operations to be performed in a particular order where each operation’s input depends on the output of the previous operation, that’s the scenario where this pattern is applicable!

Example:

Assume that you contact customer-care for some tech support. The actions involved are:

1) You listen to an automated voice and dial some numbers which redirect to the concerned person

2) You talk to the operator and he/she suggests a couple of solutions

3) You try them and if it didn’t work the operator redirects you to the next level in the hierarchy for assistance

4) Again you’ll receive some different suggestions from level 2 assistance and if those didn’t work you would get redirected to further higher levels till your query is resolved

That’s one analogy for using this design pattern.

Here you are the Client and the Customer Support system is the Request handler. On each level your request is being processed and based on the outcome, it goes to the next handler in the chain!

A better example is available here: refactoring.guru

Why Form Validation?

When we have an HTML form with multiple input fields that requires specific validations, we’ll have to write multiple if-else statements that validate all of them. Here validation is done one by one on every mandatory input field and if any of the input is invalid we don’t have to validate the remaining! So these validations are performed in a sequence and are based on the result of the previous validation! Hence this scenario is a candidate for Chain of Responsibility pattern.

Form I had to validate

(Please exclude the user-experience here! I know the UX can be improved by showing all the input related errors inline, next to the corresponding input field instead of showing one single line of error that the top. But this was exactly the requirement I had in one of my projects!)

Assume that this is the popup’s data object and each key in this object is somehow bound to the input field in the UI.

So this is the data object which needs to be validated.

Form Validation — before applying this pattern:

Notice how large one function can become when all the mandatory fields need to be validated. There are plenty of reasons to claim that writing one big function is harmful.

One function with too many if/else statements violates the “Single Responsibility Principle” as this function just does “too” many things!

Although the code looks somewhat readable, in future if we have to add new input fields, we would need to add more validations to this function which eventually grows bigger.

Also, if there is some other place in the application which also needs a subset of these validation rules, then we will have to copy-paste a couple of lines which leads to code duplication.

Validation with this pattern applied:

So to implement this pattern for validation we first need to define the base class Validator. This is going to be the type of an item in chain.

For all the validation rules we need, lets define the classes that inherits this base class.

Implement a utility class which constructs the chain by appending objects to the list.

Combining all these classes together, we’ll create ValidatorService which triggers the validation chain.

Although there are so many tiny new classes, the code is a lot more readable now and one big function which was having too many if-else statements is now refactored into several tiny ones and each function does exactly one thing!

And if there’s a need to add more validations, we can just add appropriate classes to the chain. Even better, we can either add or remove validation rules in Runtime.

[UPDATE]:

In case if there are multiple validations which only involves checking an input with a regex string, we can write one generic Validator class which takes a regex, the target input value and test it.

Here’s the implementation:

That’s it

“A design that doesn’t take change into account risks major redesign in the future.” ― Erich Gamma, Design Patterns: Elements of Reusable Object-Oriented Software

This pattern may be a bit overkill for simple validations. But for complex form validations or if more validations are expected to be added in the future, this would help in maintaining the code as each rule is modular and is loosely coupled with other rules and the client.

BUT… Is this pattern required in this scenario?

Or is there any other better way to do form validations?

Please comment on your thoughts on this! Looking forward to improvise!