DESIGN PATTERNS SERIES
Decoupling with Chain of Responsibility Pattern in C#
The Chain of Responsibility Pattern allows us to easily separate dependent parts to make code more extensible and testable.
Published in
5 min readMay 20, 2020
The article cooperates with the sample project. Walkthrough with the downloaded project is not required, but I recommend it for better understanding.
The sample project consists of two different approaches to validating the user’s data within a registration. Two processors simulate the user’s registration process.
BasicUserRegistrationProcessor.cs
follows the simple path of if statements.
public class BasicUserRegistrationProcessor
{
public void Register(User user)
{
if (string.IsNullOrWhiteSpace(user.Username))
{
throw new Exception("Username is required.");
} if (string.IsNullOrWhiteSpace(user.Password))
{
throw new Exception("Password is required.");
} if (user.BirthDate.Year > DateTime.Now.Year - 18)
{
throw new Exception("Age under 18 is not allowed.");
}
}
}
ChainPatternRegistrationProcessor.cs
is taking advantage of the Chain of Responsibility Pattern. This…