问题
I am trying to understand single responsibility principle. I have following questions.
The Single Responsibility Principle (SRP) states that there should never be more than one reason for a class to change. Usually our Resource,Service and Repository classes have create,read,update and delete method. We are changing each class to modify code for any any of these operations. Is it violating SRP? Do we need separate class for each action?
When I run sonar lint, I have seen below message.
Classes should not coupled to too many other classes.
Here I am injecting other classes using spring DI. Is there any limit on number of dependencies?
I may be missing crux of this concept. Please suggest a good resource for understanding this concept better with examples
回答1:
The SRP states that the class should only do one thing, like persisting entities in the case of repositories. I guess that you've confused "class" and "object" here: if you have several methods that could change the object's state this could be in accordance with the SRP. However the only reason for a repository class to change should have something to do with its purpose, namely persisting or retrieving entities in this case.
The Wikipedia article about the Single Responsibility Principle puts it very well.
To your second point: there is no such thing as a maximum number of dependencies a class can have, but it could be a sign for a design weakness if there are many of them.
回答2:
The Single Responsibility Principle (SRP) states that there should never be more than one reason for a class to change.
The Single Responsibility principle doesn't mean a single method or a single type of action by component/class.
It means a single responsibility in the scope of a matter.
Persistence operations makes part of the same matter.
So putting all of them in a single class doesn't violate necessary the principle.
Now if you have dozen and dozen of specific database operations, it would make sense to divide them into distinct classes having a well defined responsibility such as selecting operations, updating operations, and so for.
Usually our Resource,Service and Repository classes have create,read,update and delete method. We are changing each class to modify code for any any of these operations. Is it violating SRP?
These are distinct layers.
If you change the model of a layer, others are very often impacted as data passes between layers.
It is like if you add an information in your database, you necessary need to change your GUIs and your processing if you want see/manipulate them.
Now if you change implementation of layers, other layers should have no or very few consequences.
来源:https://stackoverflow.com/questions/47871647/classes-with-crud-methods-violating-single-responsibility-principle