Friday, December 9, 2016

SRP - Single Responsibility Principle

SRP says - Every software module should have only one reason to change.

This means that a class or similar structure should have only one job to do. It doesn't mean that a class should have only one method or property, it can have many members (methods and properties ) as long as they related to single responsibility.

Swiss knife is the real-life example where SRP is broken, that's because the tool requires alteration if any one of the item needs changes.   

Lets see SRP with the example below:
public class UserService {
      public void Register()
     {
          // validate email
          // Register User
         // send confirmation mail to user
     }

      public bool ValidateEmail()
     {
     } 


      public bool SendMail()
     {
     }

}

We have a UserService with Register method which registers the user after validating e-mail ID and then sends the e-mail confirmation to the user. In this implementation of UserService, it violets SRP, since it's not only does the user registration but also the email validation and sending confirmation e-mail to user. To overcome this issue create one more class and move ValidateEmail() and SendMail() method to it.

public class EmailService()
{
      public bool ValidateEmail()
     {
     } 


      public bool SendMail()
     {
     }

}

Now the UserService class looks as below:
public class UserService {

      public void Register()
     {
          // validate email using EmailService
          // Register User
         // send confirmation mail to user using EmailService.
     }
     
}
  
Advantages:
  • Gives a good way to identify classes at the design phase of an application and makes you think of all the way a class can change.
  • Reduces Code complexity.
  • Improves Readability.
  • Reduces Coupling.
  • Code gets better chance of cleanly evolving.
PS: SRP is not about code-reuse.

No comments:

Post a Comment