Single Responsibility Principle
What are S.O.L.I.D Principles?
Why developers should know about these principles?
When we takes a computer program , it may contains many classes. So each class of the computer program must have responsibility over a single part of that program’s functionality,which should encapsulates.(Wikipedia)
That means, there may not contain classes that are not
having any duty with the program. Every class in the program must contain a
responsibility over the program.
What do you mean by responsibility?
According to Martin, responsibility means reason to change and
concludes that a class or module should have one and only one reason to be
changed (e.g. re written)- (Wikipedia)
2) Usage
Let’s assume there is a program to generate a PDF file
according to the information that are given by the user according to the given
format by the program.
So in this scenario ,
Input – Details given
by the user according to the format that is provided by the program
Process – Generation PDF report
Output – PDF report including the details that are entered
by the user
Note : There is a one class to generate the report according
to a format.
So here the output can be changed according to several
reasons,
-
If the user entered different details apart form
the format that is given by the program
-
If user wants to send that PDF file to someone
through the system apart from downloading it
So here, the thing is do not use the same class to do both
changes that I mentioned above. It is a bad approach. Instead of using same
class to do both changes we have to use two separate classes for each change or
requirement. That’s the usage of Single Responsibility.
There is a class called Student.
This example violates Single Responsibility.
Here, Student class is for represent the Student. So Register(),Apply() are responsibilities of the Student.
So if we want to make changes to these Register or Apply responsibilities, it may be affect to the Student model either by adding an extra properties.
So when apply the Single Responsibility we have to keep these methods in a separate class.
So if a class has more than one responsibility, they become
coupled. Changes to one responsibility may restrict the class’s ability to meet
other requirements.
4) Benefits
- The class is easier to understand
- The class is more reusable
- The class is easier to maintain
Comments
Post a Comment