Monday, April 5, 2021

SOLID | Single Responsibility Principle (SRP)

Single Responsibility Principle (SRP)

Introduced by Robert C. Martin, defines responsibility as a single reason to change the class.
  • A class should have only one job to do
  • It should have a single purpose to serve
  • By a single purpose and responsibility it does not mean to be a small class with limited members in it, it can have many but it should point to a single purpose. 
  • It helps to separate the classes at the first design phase so that the complexity can be reduced and can be more extensible

Example,

public class UserService
{
    //Create user
   public void CreateNewUser()
   {
        //New user creation implementation
        //Send an email alert
        SendEmail();
    }

    //Sending an email with user-created
    public void SendEmail()
    {
        //Email sending implementation
    }
}

A developer would only be able to understand only when he or she has a clear picture of what needs to be implemented according to the requirement. 

The above example shows two methods kind of user registration which registers the user and sends an alert email. The implementation is short and sweet to understand and it looks good at the first level. But as we are looking at the single responsibility principle you can have an idea of what is wrong with it. 

Let's redesign that with Single Responsibility Principle, 

public class UserService
{
    //Create user
   public void CreateNewUser()
   {
        //New user creation implementation
        
        //Send an email alert
        EmailService.SendEmail();
    }
}

public static class EmailService
{
    //Sending an email with user-created
    public void SendEmail()
    {
        //Email sending implementation
    }
}

Now, we have created a separate class for EmailService which can only contain email-related methods. UserService should have user related tasks in it. If SendEmail() method is part of the same service then at any other service if it needs to consume it would be a redundant code. At this level the same thing becomes reusable.
 

No comments:

Post a Comment

C# Interview Prep: 100 Common Questions for 0-3 Years Experience

Common C# Interview Questions  Basics of C# Language: What is C#? C# (pronounced C sharp) is a modern, object-oriented programming language...