Tuesday, 5 September 2017

Single Responsibility Principle (SRP)

According to SRP a class should take one responsibility and there should be one reason to change that class. When a class has more than one responsibility, there are also more triggers and reasons to change that class. A responsibility is the same as “a reason for change” in this context.

  •       Base on cohesion.
  •     A class should do only one thing.
  •      Separation of concerns.



For real world example, such as famous Swiss knife. If one of them needs to be changed the whole set needs to be disturbed.



But if those items separated its simple, easy to maintain and one change does not affect the other. The same principle also applies to classes and objects as SRP in software architecture.




For Coding Example ,Check with this Employee class 


namespace SRP
{
    public class Employee
    {
        public int EmployeeId { get; set; }
        public string EmployeeName { get; set; }
        public bool InsertEmployee(Employee employee)
        {
            // Insert into employee table.
        }
        public bool DeleteEmployee(int employeeId)
        {
            // Delete the Employee in employee table.
        }
        public void GenerateReport(Employee employee)
        {
            // Report generation with employee data
        }
    }
}

Employee” class is taking 2 responsibilities,
  1. Take responsibility of employee database operation
  2. Generate employee report.
There are two reasons to change this class. That is not good approach of software Engineering.

According to SRP, one class should take one responsibility so we should write one different class for
report generation and if any change in report generation should not affect the ‘Employee” class.

public class ReportGeneration
    {
       
        public void GenerateReport(Employee employee)
        {
            // Report reneration with employee data.
        }
    }

No comments:

Post a Comment

Single Responsibility Principle (SRP)