Single Responsibility Principle (SRP)
A class should have only one reason to change, meaning that a class should only have one job. If a class has more than one reason to change, it has more than one responsibility, and these responsibilities should be separated into different classes.
Certainly! Let's consider an example in C# to illustrate the Single Responsibility Principle (SRP). Imagine we are building a system to manage employees in a company. We can start with a class `Employee` that represents an employee in the company:
```csharp
public class Employee
{
public int Id { get; set; }
public string Name { get; set; }
public decimal Salary { get; set; }
public void CalculateSalaryBonus()
{
// Calculate salary bonus logic
// ...
}
public void SaveToDatabase()
{
// Save employee to the database logic
// ...
}
}
In this example, the `Employee` class has two responsibilities:
1. **Calculating Salary Bonus**
2. **Saving to Database**
However, this violates the Single Responsibility Principle because the class has more than one reason to change. If the database schema changes or if the way salary bonuses are calculated changes, the `Employee` class would need to be modified for multiple reasons.
To adhere to the SRP, we should separate these responsibilities into different classes. Here's how you can refactor the code:
```csharp
public class Employee
{
public int Id { get; set; }
public string Name { get; set; }
public decimal Salary { get; set; }
}
public class SalaryCalculator
{
public decimal CalculateSalaryBonus(Employee employee)
{
// Calculate salary bonus logic
// ...
}
}
public class EmployeeRepository
{
public void SaveToDatabase(Employee employee)
{
// Save employee to the database logic
// ...
}
}
In this refactored version, the `Employee` class is responsible only for representing the data of an employee. The `SalaryCalculator` class is responsible for calculating salary bonuses, and the `EmployeeRepository` class is responsible for saving employee data to the database. Each class now has a single responsibility, adhering to the Single Responsibility Principle. This separation allows for more flexibility and maintainability in the codebase.