Single Responsibility Principle a Class with Multiple Methods


In this article we are going to discuss Single Responsibility Principle in C#. There are many blogs, articles are available on the internet regarding Single Responsibility Principle but in this particular article I will try to explain to you with as much as simple.

SRP with Multiple Methods

a class adhering to the Single Responsibility Principle (SRP) which have multiple methods. The key is that all the methods should contribute to fulfilling the single responsibility or purpose of that class. Each method within the class should perform a task that supports the class's main responsibility.

Example of SRP with Multiple Methods

Let's consider an example where we have a ReportGenerator class responsible for generating reports. This class can have multiple methods, each performing a specific part of the report generation process, but all contributing to the single responsibility of generating a report.

public class ReportGenerator
{
    public void GenerateReport()
    {
        string data = FetchData();
        string report = FormatReport(data);
        SaveReport(report);
    }

    private string FetchData()
    {
        // Code to fetch data from a data source
        Console.WriteLine("Data fetched.");
        return "Sample Data";
    }

    private string FormatReport(string data)
    {
        // Code to format the report
        Console.WriteLine("Report formatted.");
        return $"Formatted Report: {data}";
    }

    private void SaveReport(string report)
    {
        // Code to save the report
        Console.WriteLine("Report saved.");
    }
}

class Program
{
    static void Main()
    {
        ReportGenerator reportGenerator = new ReportGenerator();
        reportGenerator.GenerateReport();
    }
}

Explanation

GenerateReport Method - This is the main method responsible for generating the report. It coordinates the overall process by calling other private methods.
FetchData Method - Responsible for fetching data needed for the report.
FormatReport Method - Responsible for formatting the fetched data into a report.
SaveReport Method - Responsible for saving the formatted report.

Each method contributes to the single responsibility of the ReportGenerator class, which is to generate a report.


Prev /a> Next