Single Responsibility Principle with Example


Overview of Single Responsibility Principle (SRP)
 
It states that every object should have a single responsibility, and that responsibility should be entirely encapsulated by the class. There should not be more than one reason to change the class. This means class should be designed for one purpose only. This principle states that if we have 2 reasons to change for a class, we have to split the functionality in two classes. Each class will handle only one responsibility and on future if we need to make one change we are going to make it in the class which handle it. When we need to make a change in a class having more responsibilities the change might affect the other functionality of the classes. 

Intent

A class should have only one reason to change.

Example

In short, it says that a subsystem, module, class, or even a function, should not have more than one reason to change. The classic example is a class that has methods that deal with business rules, reports, and database: Below example shows how it violates the rule of single responsibility Principle. Employee class has designed to save,Modify and GetEmployeeInfo() records from Database but MAPEmployee() method is used for mapping Database columns with the Employee class  attributes which can be altered if there is any changes in DB

Public Class EmployeeService
{
public void SaveEmployeeInfo(Employee e)
{// To do something}
public void UpdateEmployeeInfo(int empId, Employee e)
{//To do Something

}
public Employee GetEmployeeInfo(int empID)
{// To do something
}

public void MAPEmployee(SqlDatareader reader)
{// To do something
}
}

We can segregate the classes into two classes which will implement only MAPEmployee, so that if there are any changes in DB no need to change EmployeeService class

Public Class EmployeeService
{
public void SaveEmployeeInfo(Employee e)
{// To do something}
public void UpdateEmployeeInfo(int empId, Employee e)
{//To do Something

}
public Employee GetEmployeeInfo(int empID)
{// To do something
}
}
Public Class ExtendEmployeeService:EmployeeService
{


public void MAPEmployee(SqlDatareader reader)
{// To do something
}
}

Conclusion

The Single Responsibility Principle represents a good way of identifying classes during the design phase of an application and it reminds you to think of all the ways a class can evolve. A good separation of responsibilities is done only when the full picture of how the application should work is well understand.


Similar Articles