Sunday, 15 February 2026

SOLID - Single Responsibility Principle

In this article we are going to see what is single responsibility principle (SRP) in SOLID. The SRP is about the class should have only one responsibility or we can say like it should talk about only one entity. For Example if it is a Employee class, then it should have behaviour and properties only about Employee. simply says the class should have only one reason to change.

First we will see a class which violating the SRP.


In the above class Salary we see that three methods

1. one is calculating Salary.

2. another one is save to DB

3. another one is Print to Salary. 

So the first one is application logic , second one is DB layer, third one is UI layer code, all are three different behaviour, now this is violating the SRP. 

How we can convert this to SRP.

Now if you see above example three classes in which each one have one responsibility, first one is business logic, second one is DB logic, third one is UI logic.

Now we can see a Logger class which is in SRP.


The above class is Logger, which have only one responsibility or talks about only one entity Logging message. if we have another method like  PrintMessage() in the class then that is irrelevant to the class then that is violating the SRP

No comments:

Post a Comment