Search code examples
springsolid-principlessingle-responsibility-principle

classes with CRUD methods violating Single Responsibility principle?


I am trying to understand single responsibility principle. I have following questions.

  1. 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?

  2. 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


Solution

  • 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.