SOLID Design Principles – Single Responsibility Principle (SRP)

 

Hey guys,

In this series i will talk about the SOLID Design Principles. We will discuss one principle in each post.

In this post we will talk about the S which is Single Responsibility Principle (SRP).

 

Single Responsibility Principle (SRP)

 

There should never be more than one reason to change a class. Robert C. Martin

We can think of responsibility of a class as a reason for change in the context of SRP and we want a class to have only one of that. This will be really important when we have an issue because we will know exactly we need to look.

solid.srp

Say we have a modem class in our application and it does 4 operations

 

Without SRP

Without SRP

interface IModem
{
    bool Dial(string phoneNumber);
    bool Hangup();
    bool SendMsg(char msg);
    char RecieveMsg();
}

 

It will make a lot of sense to divide these operations into 2 interfaces that the Modem class implements. We have divided responsibility so that each class has single reason to be modified.

 

With SRP

With SRP

This does not mean that we should start creating different classes for each of the feature or method that we are implementing. There can be different levels of segregation that we can have depending on our application.

For example – In a huge application we might want to create a math class for doing all the math related operations but in a small application we might have different classes for simple operations (add, sub, mul, div) and different class for trigonometric operations (sin, tan, cos)

Cohesion – It is a measure of how much responsibility, data and methods of a class / module are related. It can be thought of as the clarity with which the role of a class is defined within the system. We should always aim for high cohesion.

We can identify cohesion by comparing the class name and the responsibility of the class. If the class is doing something other than what its name specifies than we do not have the desired level of cohesion.

Put your code where everyone would expect to find it.

Coupling – It is the degree to which the different modules or classes are interdependent or relies on each other. We should always aim for low coupling.

The more responsibility a class has more is the likelihood of changes in the class, more the changes more is the likelihood of errors because the responsibilities within a class tend to couple with each tightly.

Interface Segregation Principle (ISP) helps us achieve the Single Responsibility Principle (SRP).

 

Any questions, comments or feedback is welcome.

Leave a Reply

Your email address will not be published. Required fields are marked *