Single Responsibility Principle

Single Responsibility Principle (SRP)

In this tutorial, we are going to discuss Single Responsibility Principle (SRP) in SOLID Principles. Let’s begin with the single responsibility principle. This principle states that “a class should have only one reason to change,” which means every class should have a single responsibility or single job, or single purpose.

Single Responsibility Principle

Take the example of developing software. The task is divided into different members doing different things as front-end designers do design, the tester does testing, and the backend developer takes care of the backend development part. Then we can say that everyone has a single job or responsibility.

Everything in the class should be related to that single purpose. It does not mean that your classes should only contain one method or property.

There can be a lot of members as long as they relate to the single responsibility. It may be that when the one reason to change occurs, multiple members of the class may need modification. It may also be that multiple classes will require updates.

Let’s understand the single responsibility principle through an example.

package com.ashok.solid.principles.srp;

/**
 * 
 * @author ashok.mariyala
 *
 */
public class Employee {
	public void getEmployeeDetails() {
		//functionality of the method  
	}

	public void calculateSalary() {
		//functionality of the method  
	}

	public void addEmployee() {
		//functionality of the method  
	}
}

The above code snippet violates the single responsibility principle. Here we have salary calculation logic with get employee details logic and add employee logic all mixed up within one class. If you have multiple responsibilities combined into one class, it might be difficult to change one part without breaking others.

Mixing responsibilities also makes the class harder to understand and harder to test, decreasing cohesion. The easiest way to fix this is to split the class into three different classes. Each has only one responsibility: adding employees, calculating salary, and getting employee details, all separated.

package com.ashok.solid.principles.srp;

/**
 * 
 * @author ashok.mariyala
 *
 */
public class Employee {
	public void addEmployee() {
		//functionality of the method  
	}
}
package com.ashok.solid.principles.srp;

/**
 * 
 * @author ashok.mariyala
 *
 */
public class PrintEmployeeDetails {
	public void getEmployeeDetails() {
		//functionality of the method  
	}
}
package com.ashok.solid.principles.srp;

/**
 * 
 * @author ashok.mariyala
 *
 */
public class Salary {
	public void calculateSalary() {
		//functionality of the method  
	}
}

Hence, we have achieved the goal of the single responsibility principle by separating the functionality into three separate classes.

Single Responsibility Principle
Scroll to top