SOLID Principles

Examples of SRP

Let's illustrate SRP with an example in C#. Suppose we have a class that handles both the creation and saving of a report.

Violating SRP

public class Report
{
    public string Title { get; set; }
    public string Content { get; set; }

    public void CreateReport(string title, string content)
    {
        Title = title;
        Content = content;
        // Logic to create the report
    }

    public void SaveToFile(string filePath)
    {
        // Logic to save the report to a file
        System.IO.File.WriteAllText(filePath, Content);
    }
}

In this example, the Report class has two responsibilities:

  1. Creating a report.
  2. Saving the report to a file.

Adhering to SRP

We can refactor the code to adhere to SRP by creating separate classes for each responsibility.


public class Report
{
    public string Title { get; private set; }
    public string Content { get; private set; }

    public void CreateReport(string title, string content)
    {
        Title = title;
        Content = content;
        // Logic to create the report
    }
}

public class ReportSaver
{
    public void SaveToFile(Report report, string filePath)
    {
        // Logic to save the report to a file
        System.IO.File.WriteAllText(filePath, report.Content);
    }
}

Now, the Report class is responsible only for creating the report, and the ReportSaver class is responsible for saving the report to a file. This adheres to SRP as each class has a single responsibility.