Java OOP Principle – Single Responsibility Principle

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

  1. Multiple responsibilities injected in the same class makes it difficult to maintain
  2. Classes cannot be loosely coupled and thus does not provide flexibility.
  3. Recompilation of dependent classes
  4. Increased Testing to ensure included changes does not break the existing functionality.
  5. Written code cannot be re-used

Advantages of using Single Responsibility Principle

  1. Performs a specific responsibility
  2. Classes are loosely coupled
  3. Written Code can be re-used
  4. Does not require validation and re-compilation of dependent classes
  5. Helps in developing more robust and scalable applications
  6. Reduces coding issues and significantly reduces overall development time.
  7. Reduces testing cycle as specific set of changes need to be tested.
  8. 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.