Single Responsibility Principle is one of the SOLID principles of object-oriented programming. There are five (5) design principles defined for developing Java application to make it more flexible, scalable and easy to maintain.
SOLID is an acronym for the below given 5 design principles.
- Single Responsibility Principle
- Open –Closed Principle
- Liskov Substitution Principle
- Interface Segregation Principle
- Dependency Inversion Principle
The blog covers the 1st design principle – Single Responsibility Principle.
Robert C. Martin first published the theory of SOLID Principles 2000 paper Design Principles and Design Patterns.
The Design Principle – Single Responsibility depicts that every class should have the single responsibility to perform and ensure that the dependency should not be injected which makes the class changed again and again.
As per Robert C. Martin, he described as
“A class should have only one reason to change”
With the Current Business needs, there are many possible reasons that the implemented classes might get into change if they are not loosely coupled and have multiple dependent features within the same class. With such classes, the change in the requirement, requires the change in the already implemented classes. This happens so as each class is trying to perform more than a specific set of responsibilities and also contradicts the 1st OOP Principle of Single Responsibility.
Challenges with the above approach
Multiple changes in the existing class
- Multiple responsibilities injected in the same class makes it difficult to maintain
- Classes cannot be loosely coupled and thus does not provide flexibility.
- Recompilation of dependent classes
- Increased Testing to ensure included changes does not break the existing functionality.
- Written code cannot be re-used
Advantages of using Single Responsibility Principle
- Performs a specific responsibility
- Classes are loosely coupled
- Written Code can be re-used
- Does not require validation and re-compilation of dependent classes
- Helps in developing more robust and scalable applications
- Reduces coding issues and significantly reduces overall development time.
- Reduces testing cycle as specific set of changes need to be tested.
- Easy maintainability
Consider the MVC Framework, which segregates the Model, View and Controller and implements several classes internally which provide specific execution.
Similarly, the usage of Micro Services can have multiple API but each API will have separate resources for executing a specific set of responsibility. Example – The Customer API could have multiple resources as like createCustomer, updateCustomer, deleteCustomer, getCustomer, getCustomerList and so on. Each resource segregates and performs specific operation.