Thursday, February 9, 2012

Single Responsibility Principle (SRP)

Single Responsibility Principle (SRP)

Single Responsibility Principle states that ‘a class or module should have only one responsibility’ where a responsibility is a ‘reason for change’. In plain English this means that a class should serve a single purpose (responsibility). Only the responsibility dictates a change in the class. If a class has more than one responsibility then it will lead to bad design later on. Changes made to a class should not affect others. This principle follows Dijkstra’s ‘Separation of Concern (SOC)’ principle.

Let me demonstrate this concept with a simple example. Consider the following class:


public class Employee {

 public EmployeeDTO GetEmployee (int employeeID)
{
  // perform database lookup and get the employee
 }

 public double CalculateSalary (int employeeID)
 {
  // perform database lookup and calculate salary
}
}


The above Employee class is serving two purposes. First, it returns an employee and second it calculates the salary of the employee. The first function is justified, however; the Employee class should know anything about calculating the salary of an employee. This means every time the salary calculating formula changes, the Employee has to be modified. This process should be handled by a separate class. So the above code can be modified as following:

public class Payroll
{
 public double CalculateSalary (int employeeID)
 {
  // calculate and return the employee salary
 }
}

public class Employee {

 public EmployeeDTO GetEmployee (int employeeID)
{
  // perform database lookup and get the employee
 }

 public double CalculateSalary (int employeeID)
 {
  Payroll pay = new Payroll ();
  return pay.CalculateSalary (employeeID);
}
}


I am sure you can spot the change in the above code. The responsibility of calculating the salary is now handled by the Payroll class. The Employee class is no longer concerned about how the salary is calculated. It just invokes a method of the Payroll class and gets the required results. The Payroll class can be changed without affecting the Employee class and vice versa.

One may argue that the Single Responsibility Principle can result in a plethora of classes. The answer is yes it can. However, having more classes which are simple to manage is better than having a few but complex classes. Managing complex classes is always a burden on the programmer. Simple classes make refracting easy for any future changes. 


Reference:
http://dotnetpost.blogspot.in/2010/03/single-responsibility-principle.html

No comments:

Post a Comment