Single Responsibility Principle (SRP or S in SOLID principles) in C#

What is Single Responsibility Principle?

 Robert Martin in the principles of OOD says:  “There should never be more than one reason for a class to change.” This means a class should concentrate on doing one thing. The SRP says a class should focus on doing one thing, or have one responsibility. This doesn’t mean it should only have one method, but instead all the methods should relate to a single purpose (i.e. should be cohesive).
For example, an Invoice class might have the responsibility of calculating various amounts based on it’s data. In that case it probably shouldn’t know about how to retrieve this data from a database, or how to format an invoice for print or display.
A class that adheres to the SRP should be easier to change than those with multiple responsibilities. If we have calculation logic and database logic and display logic all mixed up within one class it can be difficult to change one part without breaking others. Mixing responsibilities also makes the class harder to understand, harder to test, and increases the risk of duplicating logic in other parts of the design (decreases cohesion, functionality has no clear place to live).
Violations of the SRP are pretty easy to notice: the class seems to be doing too much, is too big and too complicated. The easiest way to fix this is to split the class.
The main trick in following the SRP is deciding how to define the single responsibility. There may be many ways to dissect a feature into responsibilities, but the ideal way is to use responsibilities that are likely to change independently, hence the official description: “A class should have one, and only one, reason to change”.

 

SOLID Principles in C#

What are SOLID principles? 

SOLID is an acronym for the first 5 principles of object-oriented design:

S stands for SRP “The Single Responsibility Principle”:  a class should have one, and only one, reason to change.
O stands for OCP “The Open Closed Principle”: you should be able to extend a class’s behavior, without modifying it.
L stands for LSP “The Liskov Substitution Principle”: derived classes must be substitutable for their base classes.
I stands for ISP “The Interface Segregation Principle”: make fine grained interfaces that are client specific.
D stands for DIP “The Dependency Inversion Principle”: depend on abstractions not on concrete implementations.

 

Copyright © All Rights Reserved - C# Learners