Tuesday, May 2, 2023

SOLID - Single Responsibility Principle explanation with sample C# code

The Single Responsibility Principle (SRP) is a principle in object-oriented programming that states that a class should have only one reason to change. In other words, a class should have only one responsibility or job.

Here is an example of how to implement the SRP in C#:
public class Customer
{
    public string Name { get; set; }
    public string Email { get; set; }
    public void Save()
    {
        // Save the customer to the database
    }
}

public class CustomerEmailer
{
    public void SendEmail(Customer customer, string message)
    {
        // Send an email to the customer
    }
}
In this example, we have two classes: 'Customer' and 'CustomerEmailer'. The 'Customer' class has the responsibility of storing customer information and saving it to a database. The 'CustomerEmailer' class has the responsibility of sending emails to customers.

By separating these responsibilities into separate classes, we have made our code more modular and easier to maintain. If we need to make changes to how we store customer information, we can do so without affecting the email sending functionality. Similarly, if we need to change how we send emails, we can do so without affecting how we store customer information.

Overall, adhering to the SRP helps us create code that is more flexible and easier to maintain over time.

No comments:

Post a Comment