The Single Responsibility Principle (SRP)

Category : SOLID | Sub Category : SOLID Principles | By Prasad Bonam Last updated: 2024-01-10 09:57:22 Viewed : 180


The Single Responsibility Principle (SRP) is one of the SOLID principles of object-oriented design. It states that a class should have only one reason to change, meaning that a class should have only one responsibility or job. In other words, a class should encapsulate only one aspect of functionality.

Lets consider a real-world example to illustrate the Single Responsibility Principle. Suppose you are designing a system for managing employees, and you have a class that represents an employee:

java
public class Employee { private String name; private String employeeId; private double salary; public Employee(String name, String employeeId, double salary) { this.name = name; this.employeeId = employeeId; this.salary = salary; } public void calculatePay() { // Logic for calculating the employee`s pay System.out.println("Calculating pay for " + name); // ... } public void saveToDatabase() { // Logic for saving employee details to the database System.out.println("Saving " + name + " to the database"); // ... } }

In this example, the Employee class has two responsibilities: calculating pay and saving employee details to the database. This violates the Single Responsibility Principle.

To adhere to the Single Responsibility Principle, we can refactor the class into two separate classes, each with a single responsibility:

java
public class Employee { private String name; private String employeeId; private double salary; public Employee(String name, String employeeId, double salary) { this.name = name; this.employeeId = employeeId; this.salary = salary; } public void calculatePay() { // Logic for calculating the employee`s pay System.out.println("Calculating pay for " + name); // ... } }
java
public class EmployeeDatabase { public void saveToDatabase(Employee employee) { // Logic for saving employee details to the database System.out.println("Saving " + employee.getName() + " to the database"); // ... } }

Now, the Employee class is responsible only for calculating pay, and the EmployeeDatabase class is responsible for saving employee details to the database. This separation of concerns adheres to the Single Responsibility Principle and makes the code more maintainable and flexible. Each class now has a single reason to change, and modifications to one aspect of the system are less likely to impact other unrelated aspects.

Search
Sub-Categories
Related Articles

Leave a Comment: