by BehindJava

What is Single Responsibility Principle in SOLID Design Principles of Object Oriented Programming

Home » java » What is Single Responsibility Principle in SOLID Design Principles of Object Oriented Programming

Single Responsibility Principle

  • Any class that you create should have just one responsibility.

Example: Suppose you are creating an e-commerce website and you are dealing with many components. Here we have a class for order management where we have different functionalities pertaining to order management like fetch order details, manage order, cancel order, order tracking, etc. and in this case order management class should be responsible for only a Single responsibility i.e., order management life cycle.

  • If any modification is required to a class, it should have a single update or only one reason for the change.

Example: Create an API to get ListOfEmployees

public class EmployeeDetails{

    @GetMapping("/get/employees")
    public String getEmployeeDetailsList(int projectId){
        //code to fetch employees list
    }

    @PostMapping("/addEmployee")
    public void addEmployee(Employee emp)
    {
        //add employee here 
    }
}

Is Single Responsibility Principle is preserved?

  • It depends upon the code we write inside the EmployeeDetails class.
  • In the method getEmployeeDetailsList(), the functionality is to fetch the list of employees and here we can write the database connection code as well as for getting the employees and we have one more method called addEmployee(), which is responsible for adding the employees.
  • Suppose, We are using oracle database connection in the EmployeeDetails class and sooner or later due to database migration to mysql or postgresql there will be the connection changes in the EmployeeDetails class which breaks the Single Responsibility Principle.

As a best practice to not break the single responsibility principle in the above scenario we can delegate the code for creating database connection in a separate class or package DAO altogether.

The whole idea behind this design principle is to modularize or divide the application into each package with each class that holds the single responsibility principle. So that direct dependencies can avoided.