The Single Responsibility Principle (SRP) states that a class should have only one reason to change. In other words, a class should have only one responsibility or job to do. Here's an example of SRP in C#:
// Bad example: One class that does too much
public class Order
{
public void Save(Order order)
{
// Save the order to the database
}
public void Update(Order order)
{
// Update the order in the database
}
public void Delete(Order order)
{
// Delete the order from the database
}
public void SendEmail(Order order, string emailAddress)
{
// Send an email to the customer
}
}
In the above example, the Order class has multiple responsibilities: it saves, updates, deletes orders from the database, and sends emails to customers. This violates the SRP because if any of these responsibilities changes, the entire class needs to be modified.
Here's an example of how to apply SRP in C#:
// Good example: Separate classes for each responsibility
public class Order
{
public void Save(Order order)
{
// Save the order to the database
}
public void Update(Order order)
{
// Update the order in the database
}
public void Delete(Order order)
{
// Delete the order from the database
}
}
public class EmailService
{
public void SendEmail(Order order, string emailAddress)
{
// Send an email to the customer
}
}
In the above example, the Order class is responsible only for handling orders, while the EmailService class is responsible for sending emails. This ensures that each class has only one responsibility, making it easier to modify and maintain the code over time.
0 Comments