I had a problem to understand this for a long long time! You can’t believe how hard is it when you don’t understand the principle and try to adapt it! Mission impossible! Recently I spent some time again to read more about OOP principles and first step of SOLID is ‘S’.. Single Responsibility introduced by Uncle Bob. So let’s break it down:
Responsibility: Reason to change!!!
Single: One
Rephrase: One Reason to change!
Easy so what is a reason then? ACTOR!
OMG you just add more vocabulary!! What is Actor?
OK so we need to understand little a bit more of UML, Action means: An Actor models a type of role played by an entity that interacts with the subject (e.g., by exchanging signals and data), but which is external to the subject.
I don’t understand give me an example!!
Think below class as an example:
Employee class above has couple of functions. Is this class violating SRP? Yes! Why?
1. Load and Save functions, who will ask you to change them? DBAs
2. CalculatePay, CalculateHoliday functions, who will ask you to change them? Accountants
3. HoursWorked, HourlyRate functions, who will ask you to change them? Auditors
So three different “Actor”s exists in our example!
WOW! fascinating!
Now we understand that “Actor” and “Responsibility” is related to context. In some other context may be a class has one responsibility and in other context it has more than one. So for making your architecture and make sure you are not violating SRP you need to understand USE CASE and ACTOR and in REFACTOR process we can make decision about are we violating SRP!
Enjoy REFACTORING! And remember detecting violation SRP you need to understand user’s need and have good logic.
Saeed
December 13, 2016 — 7:36 am
Thanks for the post. It made the SRP very easy actually. In this case, I think interfaces would help a lot to refactor a class with other dependencies. Then we can have a class with its dependents injected into it. 😉
zanganeh
December 14, 2016 — 7:46 pm
Hey mate
Nice to see u here. Great on u. Yeah exactly and u can define dependency with interface.
See u
Aria
HR Rony
April 22, 2017 — 1:40 am
Excellent and well explaination. Thank you.