SOLID principles are a set of five object-oriented design principles that encourage developers to create understandable, readable, and testable code.
The Single Responsibility Principle (SRP) states that:
A class should have only one reason to change, which means that it should have only one responsibility.
In other words, each software component should be designed to perform a single specific task, making it easier to modify, extend, and maintain the code.
Violation of the principle
Consider a scenario where you have an Employee
class. This class is responsible not only for managing the details of an employee but also for calculating their salary and storing the related data in a database.
public class Employee
{
public Guid Id { get; set; }
public string? FirstName { get; set; }
public string? LastName { get; set; }
public decimal Salary { get; set; }
public decimal CalculateSalary()
{
// Calculate the employee's salary
}
public void SaveEmployee()
{
// Save employee data to the database
}
}
This class violates the SRP as it handles multiple responsibilities: storing employee information, calculating the salary, and saving the data in the database.
If we wanted to change the way the salary is calculated or the way the data is saved, we would have to change the class itself. This will increase the risk of introducing errors and make the code more difficult to understand and maintain.
Application of the principle
To comply with the SRP, we can divide the responsibilities into separate classes.
public class Employee
{
public Guid Id { get; set; }
public string? FirstName { get; set; }
public string? LastName { get; set; }
public decimal Salary { get; set; }
}
public class SalaryHelper
{
public decimal CalculateSalary(Employee employee)
{
// Calculate the employee's salary
}
}
public class EmployeeRepository
{
public void SaveEmployee(Employee employee)
{
// Save employee data to the database
}
}
In this example, we have split the responsibilities into three classes:
-
Employee
which contains only the employee information. -
SalaryHelper
which takes care of calculating the salary. -
EmployeeRepository
which handles saving the employee's data in the database.
Now, if we wanted to change the way the salary is calculated or the way the data is saved, we could do so by modifying only the corresponding class, without affecting the other parts of the system.
Conclusion
In this article, we have examined the Single Responsibility Principle, which instructs us to design classes that have only one responsibility or job. This involves separating concerns by creating multiple classes, each handling a single responsibility. Furthermore, it makes the code more maintainable and testable, minimizing the impact that changes in one responsibility can have on other parts of the code.
Top comments (2)
Thank you for sharing these articles.
Thank you for taking your time to read my articles 🙏