Single Responsibility Principle In C#

Single Responsibility Principle

We will be discussing the Single Responsibility Principle also known as SRP, as one of the SOLID principles of object-oriented programming and how to implement it when designing our software.

This principle said that each class should have one responsibility, one single purpose. This means that a class will do only one job, which leads us to conclude it should have only one reason to change.

Example

Let us define a class that contains code that changes the text and printing the text in some way.

Initialize the class (StringManipulating.cs) in this class there are two methods one is AppendString () second is PrintString () in this case SRP principle is not to work because of two responsibilities in one class.

public class StringManipulating {
    private string text;
    public StringManipulating(string text) {
        this.text = text;
    }
    public string GetString() {
        return text;
    }
    public void AppendString(string newText) {
        text = (string) text.Concat(newText);
    }
    public void PrintText() {
        Console.WriteLine(value: GetString());
    }
  }
}

Again, Modify the Code

Initialize the class (Printing.cs) and move the printText Method to this class.

public class Printing {
    readonly StringManipulating StringManipulating = new StringManipulating("Nirmal Dayal");
    public void PrintText() {
        Console.WriteLine(value: StringManipulating.GetString());
    }
}

Conclusion

Even though the name of the principle is self-explanatory, we can see how easy it is to implement incorrectly. Make sure to distinguish the responsibility of every class.


Next Recommended Reading Solid Principles In C#