Single Responsibility Principle

single responsibility principle

What is Single Responsibility Principle?

Single Responsibility Principle, also known as SRP is the first principle from the set of SOLID Principles.

A class should have only one reason to change.

Robert C. Martin

That means a class should have responsibility for a single part of the program’s functionality. Overloading a class with several functionalities leads to the below problems.

  1. The class will grow large and will be difficult to manage.
  2. It will be difficult to unit test it.
  3. In order to modify one functionality, we have to modify entire class. Therefore, the class will undergo more frequent modifications. As a result, more chances of introducing bugs.
  4. This will also require more amount of manual testing.

For example, consider a registration form, and see how it can break SRP and how to fix them.

Registration class does below functions

  1. Get input from user.
  2. Validate Input.
  3. Save data into database.
  4. Trigger confirmation email.

One can create a class for this as below

class RegisterationForm
{
    private void RegisterUser()
    {
	//Gether input
	//Validate
	//Add User to Database
	//Notify user
    }
}

How does it break SRP?

A class (and a method) doing so many things and thus broken SRP. If you want to change the storage from MS SQL to SQL Server, you will end up changing class and this can lead to undesirable effects. You will also have to test other functionalities in that class to make sure they are not affected.

“Remember, changes are not always as small. They can modify to global variables and that can become a nightmare”.

How to fix SRP violation?

Here we can split this class into 4 different classes as RegistrationForm, Validator, DatabaseHelper, and EmailHelper.

class RegisterationForm
{
    private void GetherInputs()
    {
       
    }
}
class Validator
{
    private void Validate()
    {
    }
}
class DBHelper
{
    private void AddUserToDB()
    {
    }
}
class EmailHelper
{
    private void SendEmail()
    {
    }
}

We have divided one large class into multiple smaller classes. As a result, these classes are now easy to maintain and unit testable. You can safely make changes in one class without affecting others. Therefore, less amount manual testing.

Single Responsibility Principle

Leave a Reply

Your email address will not be published.

Coding Crest Back To The Top