In my previous article I wrote about what they are and why to use Solid Principles in C#.
In this article, I am going to show you when and how to use the Single Responsibility Principle in C# with an example project. You can find the repository on GitHub.
The master branch shows the initial code used in the example. There are separate tags and branches for each of the all solid principles that you can review or download as well. Here are links you can use to jump to these tagged versions in your browser:
What is the Single Responsibility Principle (SRP) in C#?
The Single Responsibility Principle is one of the SOLID design principles. We can reuse the definition from Wikipedia. The single-responsibility principle (SRP) is a computer-programming principle that states that every module, class or function in a computer program should have responsibility over a single part of that program’s functionality, and it should encapsulate that part. Robert C. Martin defines a responsibility as a reason to change, and concludes that a class or module should have one, and only one, reason to be changed.
To better understand it, we need to divide the definition into two parts:
- Single Responsibility A class/method/function should have only a single responsibility.
- A reason to change A class or method should have only one reason to change. About the “reason” Martin clarified that this principle is about people/role. It is people who request changes.
Why should you use the Single Responsibility Principle (SRP)?
- Reduction in complexity of a code. A code is based on its responsibility and functionality. So, it reduces the code complexity.
- Increased readability, extensibility and maintenance. As each method has a single functionality so it is easy to read and maintain.
- Reusability and reduced error. As code separates based functionality so you can reuse the code somewhere else in an application.
- Reduced coupling. It reduced the dependency code. A method’s code doesn’t depend on other methods.
- Better testability. In the maintenance, when a functionality changes then we don’t need to test the entire model.