Single Responsibility Principle

By | September 27, 2020

Single Responsibility Principle (SRP)

In our application-level code, we define model classes to represent real-time entities such as Employee, Person, Admin etc. Most of these classes are examples of SRP or Single responsivity Principle because when we need to change the state of an Employee only then we will modify an Employee class and if we what to change the state of an Admin only then we will modify an Admin class and so on.

When a class handles more than one responsibility, if we make any changes to the functionalities that might affect others. This is not so bad if you have a smaller application but can become a nightmare when you work with complex, enterprise-level applications. You make sure that each module encapsulates only one responsibility, you can save a lot of testing time and create a more maintainable architecture.

For example, Let’s say we have Three classes as Employee, Person, and Admin. All have single responsibility to store their specific state or information. If we want to change the state of a Person then we do not need to modify the class Admin and vice-versa.

Why is this Principle Required?

When the Single Responsibility Principle is followed then writing test cases would be easier. The class will have fewer test cases. Fewer functionalities also mean very few dependencies to other classes. It helps to better code organization since smaller and well-purposed classes are easier to maintain

An example to clarify this principle:

Suppose the developer is asked to implement a UserSetting service where the user can change the settings but before that the user has to be authenticated. One way to implement this would be:

All looks good as long as you would want to reuse the checkAccess(User user) code at some other place Or If the developer wants to make changes to the way checkAccess(User user) is being implemented. In these two cases, The Developer would end up changing the same class and in the first case, The Developer would have to use UserSettingService to check for access as well.
There is a way to correct this UserSettingService, split the UserSettingService into UserSettingService and SecurityService, and move the checkAccess(User user) code into SecurityService so that it will align to the Single Responsibility Principle.

You May Also Like:

Singleton Pattern
Prototype Pattern
Factory Pattern
Abstract Factory Pattern
Builder Pattern

That’s all about the Single Responsibility Principle
If you have any feedback or suggestion please feel free to drop in below comment box.

Leave a Reply

Your email address will not be published.