SOLID - Single Responsibility Principle With C#

The Single Responsibility Principle is one of the SOLID design principles. We can define it in the following ways,

  1. A reason to change
    A class or method should have only one reason to change.

  2. Single Responsibility
    A class or method should have only a single responsibility.
When a class has more than one responsibility, there are also more reasons to change that class.

 

Single Responsibility Principle
Figure 1 - Single Responsibility Principle

 

SRP Benefits

The SRP has many benefits to improve code complexity and maintenance. Some benefits of SRP are following,

  1. Reduction in complexity of a code
    A code is based on its functionality. A method holds logic for a single functionality or task. So, it reduces the code complexity.

  2. Increased readability, extensibility, and maintenance
    As each method has a single functionality so it is easy to read and maintain. 

  3. Reusability and reduced error
    As code separates based functionality so if the same functionality uses somewhere else in an application then don’t write it again.

  4. Better testability
    In the maintenance, when a functionality changes then we don’t need to test the entire model.

  5. Reduced coupling
    It reduced the dependency code. A method’s code doesn’t depend on other methods.
SRP Example with C#

In this article for discussion and explanation purposes, I am introducing to you, two fictional characters Mark (a .NET developer) and Bob (a Tech Lead).

The story begins on the day when Bob contacts Mark and asks him to take up a role of an architect in his project called “Employee Management System”. We will see how Mark progresses his knowledge about Single Responsibility Principle day by day and how finally he come up with a great solution.

Intial Development

Bob (Tech Lead) explains requirements to Mark (a .Net developer). One of the primary requirements was to build a module which will have employee registration functionality.

How Mark Started

Mark defines a class named EmployeeService. It holds both employee data and registration operation as per following code snippet.

 

  1. namespace SRPApp  
  2. {  
  3.     public class EmployeeService  
  4.     {  
  5.         public string FirstName { get; set; }  
  6.         public string LastName { get; set; }  
  7.   
  8.         public void EmployeeRegistration(EmployeeService employee)  
  9.         {  
  10.             StaticData.Employees.Add(employee);  
  11.         }  
  12.     }  
  13. }  

 

Mark uses local storage to store data rather than database so he defines another class named StaticData. It has a property to store employee list. The following code snippet is for the same.

 

  1. using System.Collections.Generic;  
  2.   
  3. namespace SRPApp  
  4. {  
  5.     public class StaticData  
  6.     {  
  7.         public static List<EmployeeService> Employees { get; set; } = new List<EmployeeService>();  
  8.     }  
  9. }  

 

To keep it simple, Mark chooses console application for UI interaction. It could be a web, windows or mobile application. The following code snippet  is for user interaction. It’s an entry point for the application.

 

  1. using System;  
  2.   
  3. namespace SRPApp  
  4. {  
  5.     class Program  
  6.     {  
  7.         static void Main(string[] args)  
  8.         {  
  9.             EmployeeService employeeService = new EmployeeService  
  10.             {  
  11.                 FirstName = "John",  
  12.                 LastName = "Deo"  
  13.             };  
  14.             employeeService.EmployeeRegistration(employeeService);  
  15.             Console.ReadKey();  
  16.         }  
  17.     }  
  18. }  

 

Demonstration

Since the module was ready, Mark demonstrated the same to Bob, and Bob appreciates the architecture. All things are looking good and working as per expectation such as

  1. He defines a separate class for employee’s functionality named EmployeeService rather than performing the operation in the UI/entry program.
  2. The method performs a registration process. Data stores in fields and pass via object rather than parameters.
  3. He defines a separate class for employee storage which is static.

But, it didn't end the application. He added new requirements in this registration process. He said,

  1. We need to store employee email address with existing fields.
  2. When an employee registers then he/she gets an email.

Bob requested Mark to implement these changes in this existing application.

Problem with Preceding Design

There are two requirements. Both requirements have changed, those are totally different. One is changing the data; whereas another one is impacting the functionality. Hence, we have two different types of reason to change a single class. So, it violates the SRP Principle.

Mark realized that he should develop code in this way that data and functionality can be separated.

Improve Development

Mark has an understanding of the requirements. He knows very well where he needs to change in the existing code so he doesn't have to worry about it. But he needs to implement these changes without violating SRP. In essence, he knows that there should be two classes one for employee data and another for employee functionality. So, both changes will be implemented in two classes.

Mark starts application development as per the new requirements. He defines a new class named Employee for data as per following code snippet.

  1. namespace SRPApp  
  2. {  
  3.     public class Employee  
  4.     {  
  5.         public string FirstName { get; set; }  
  6.         public string LastName { get; set; }  
  7.         public string Email { get; set; }  
  8.     }  
  9. }  

As he uses local storage to store data so he updates StaticData class as well. The following code snippet is for the same

  1. using System.Collections.Generic;  
  2.   
  3. namespace SRPApp  
  4. {  
  5.     public class StaticData  
  6.     {  
  7.         public static List<Employee> Employees { get; set; } = new List<Employee>();  
  8.     }  
  9. }  

Mark defines registration and mail sending functionality in the EmployeeService class. This class holds two methods, one for registration of employee while another method is for sending mail to the employee. Each method defines as per functionality so that these don’t violate SRP. The following code snippet is for the same.

  1. using MailKit.Net.Smtp;  
  2. using MailKit.Security;  
  3. using MimeKit;  
  4. using System.Threading.Tasks;  
  5.   
  6. namespace SRPApp  
  7. {  
  8.     public class EmployeeService  
  9.     {  
  10.         public async Task EmployeeRegistration(Employee employee)  
  11.         {  
  12.             StaticData.Employees.Add(employee);  
  13.             await SendEmailAsync(employee.Email, "Registration""Congratulation ! Your are successfully registered.");  
  14.         }  
  15.         private async Task SendEmailAsync(string email, string subject, string message)  
  16.         {  
  17.             var emailMessage = new MimeMessage();  
  18.   
  19.             emailMessage.From.Add(new MailboxAddress("Mark Adam""madam@sample.com"));  
  20.             emailMessage.To.Add(new MailboxAddress(string.Empty, email));  
  21.             emailMessage.Subject = subject;  
  22.             emailMessage.Body = new TextPart("plain") { Text = message };  
  23.   
  24.             using (SmtpClient smtpClient = new SmtpClient())  
  25.             {  
  26.                 smtpClient.LocalDomain = "sample.com";  
  27.                 await smtpClient.ConnectAsync("smtp.relay.uri", 25, SecureSocketOptions.None).ConfigureAwait(false);  
  28.                 await smtpClient.SendAsync(emailMessage).ConfigureAwait(false);  
  29.                 await smtpClient.DisconnectAsync(true).ConfigureAwait(false);  
  30.             }  
  31.         }  
  32.     }  
  33. }  

The preceding code is developed in .NET Core, that’s why .NET Core MailKit Nuget package is used to send an email. This email send code is used for demonstration purpose. It will be worked with valid credentials and domain.

As Mark uses same console application for UI interaction so he updates it as per following code snippet.

  1. using System;  
  2.   
  3. namespace SRPApp  
  4. {  
  5.     class Program  
  6.     {  
  7.         static void Main(string[] args)  
  8.         {  
  9.             Employee employee = new Employee  
  10.             {  
  11.                 FirstName = "John",  
  12.                 LastName = "Deo",  
  13.                 Email = "jdeo@sample.com"  
  14.             };  
  15.             EmployeeService employeeService = new EmployeeService();  
  16.             employeeService.EmployeeRegistration(employee).Wait();  
  17.             Console.ReadKey();  
  18.         }  
  19.     }  
  20. }  
Demonstration

Since the module was ready, Mark demonstrated the same to Bob, and Bob again appreciates the architecture. All things are looking good and working as per expectation such as,

  1. He defines separate classes for both employee data and functionality.
  2. The methods are separated based on functionalities.
  3. He defines a separate class for employee storage which is static.
Problem with Preceding Design

The preceding code is working perfectly but it is still violating the Single Responsibility Principle. The EmployeeService class holds two methods ,one for registration of employee while another method is for sending mail to the employee. The email sending functionality is not related to the employee entity directly. The email send and employee registration are totally different functionalities. If we change email sending process such as change provider, add attachment and use SSL etc then EmplyeeService class should not be changed but it isn't possible in preceding code.

Bob explained to Mark that a class should have only reason to change and have a single responsibility. The EmployeeService class has two responsibilities so it violates the SRP principle.  It doesn’t mean that a class can’t have more than one method. A class can have multiple methods but these are related to one entity of the application. In other words, EmployeeService class can have multiple methods related to the Employee entity such as registration, update and delete etc.. Mark understood that what he did wrong here and how violates the SRP principle. Now, he knows about the Single Responsibility Principle. He starts to update in existing code for SRP.

Final Development

Mark has an understanding that a class should have a single responsibility. He knows very well where he needs to change in the existing code. But he needs to implement these changes without violating SRP.

Mark knows that he needn’t build the entire application. He needs to change in the email sending functionality. He needs to make it independently so that it could be used as another place in the application. So, there are two changes in the application. Email sending code should be removed from EmployeeService class. He needs to define a new class for email sending functionality.

He defines a new class named EmailService to send email as per following code snippet.

  1. using MailKit.Net.Smtp;  
  2. using MailKit.Security;  
  3. using MimeKit;  
  4. using System.Threading.Tasks;  
  5.   
  6. namespace SRPApp  
  7. {  
  8.   public  class EmailService  
  9.     {  
  10.         public async Task SendEmailAsync(string email, string subject, string message)  
  11.         {  
  12.             var emailMessage = new MimeMessage();  
  13.   
  14.             emailMessage.From.Add(new MailboxAddress("Mark Adam""madam@sample.com"));  
  15.             emailMessage.To.Add(new MailboxAddress(string.Empty, email));  
  16.             emailMessage.Subject = subject;  
  17.             emailMessage.Body = new TextPart("plain") { Text = message };  
  18.   
  19.             using (SmtpClient smtpClient = new SmtpClient())  
  20.             {  
  21.                 smtpClient.LocalDomain = "paathshaala.com";  
  22.                 await smtpClient.ConnectAsync("smtp.relay.uri", 25, SecureSocketOptions.None).ConfigureAwait(false);  
  23.                 await smtpClient.SendAsync(emailMessage).ConfigureAwait(false);  
  24.                 await smtpClient.DisconnectAsync(true).ConfigureAwait(false);  
  25.             }  
  26.         }  
  27.     }  
  28. }  

Mark uses the preceding code to send an email and call it in EmployeeService as per the following code snippet.

  1. using System.Threading.Tasks;  
  2.   
  3. namespace SRPApp  
  4. {  
  5.     public class EmployeeService  
  6.     {  
  7.         public async Task EmployeeRegistration(Employee employee)  
  8.         {  
  9.             StaticData.Employees.Add(employee);  
  10.             EmailService emailService = new EmailService();  
  11.             await emailService.SendEmailAsync(employee.Email, "Registration""Congratulation ! Your are successfully registered.");  
  12.         }         
  13.     }  
  14. }  

There is no change in the rest of the application.

Demonstration

Mark demonstrated the same to Bob. Now, it follows the Single Responsibility Principle. As he defined classes based on responsibilities and method based on individual functionality such

  1. He defines separate classes for employee data, functionality, email sending, UI interaction and data storage.
  2. Each class has a single responsibility and there is only one reason to change a class and method.

Now, Mark has implemented the Single Responsibility Principle in the application using C#. Bob seems happy because all his requirements seem satisfied and Mark is also happy because now he has become champ in the Single Responsibility Principle.

Conclusion

The SRP principle states that if we have two reasons to change for a class, we have to split the functionality into two classes. Each class will handle only one responsibility and in  the future, if we need to make one more change we are going to make it in the new class which handles it.

If we put more than one functionality in one class then it introduces coupling between two functionalities. So, if we change one functionality there is a chance we broke coupled functionality,  which requires another round of testing to avoid any bug in the production environment.

It reduces bug fixes and testing time once an application goes into the maintenance phase. It follows the DRY principle.