- Open Close Principle (OCP)
- Dependency Inversion Principle (DIP)
- Interface Segregation Principle (ISP)
- Single Responsibility Principle (SRP)
- Liskov's Substitution Principle (LSP)
In this article, i will explain Single Responsibility Principle.
Purpose / Reason
Each class or module should be responsible only one task. For instance, if you have one Employee class to update Employee information, calculate salary and tax. You have more than one reason to modify Employee class. I mean, when you need to change algorithm of calculating salary or tax, you have to change same class. In our purpose, you have only one reason to change class or module.
Key Principle
There should never be more than one reason for a class to change.
Implementation
For instance, you have one Employee class which is responsible for calculation salary and tax, modify Employee information and sending hours reports to managers.
Bad Example :
Bad Example :
public interface IEmployeeManager { void SendHourReports(); Money CalculateSalary(); double CalculateTax(); void UpdateEmployee(Employee employee); void CreateEmployee(Employee employee); }
As you see Employee class has more than one task to perform. Instead of designing Employee class like that, it's better to separate similar functionalities into three classes. Look at good example.
Good Example :
Good Example :
public interface ISalary { Money CalculateSalary(); double CalculateTax(); } public interface IReport { void SendHourReports(); } public interface IEmployeeDatabase { void UpdateEmployee(Employee employee); void CreateEmployee(Employee employee); }
I divide Employee class into three different classes which are ISalary, IReport, IEmployeeDatabase . Because, Employee class actually has three main functionalities :
- Salary functionalities
- Employee report s
- Database behaviors
Summary
If a class has more than one responsibility, then there will be more than one reason to modify class or module. Preventing this, you need to be able to separate classes or modules into more than one classes or module. Otherwise responsibilities become coupled and change is a manifest through a change in a responsibility among the classes or modules.