Does the single responsibility principle mean that your validation rules should be external to the entity?
If so do you use one class per validation rule?
The Single Responsibility Principle (SRP) The idea behind the SRP is that every class, module, or function in a program should have one responsibility/purpose in a program. As a commonly used definition, "every class should have only one reason to change".
As the name suggests, this principle states that each class should have one responsibility, one single purpose. This means that a class will do only one job, which leads us to conclude it should have only one reason to change.
The argument for the single responsibility principle is relatively simple: it makes your software easier to implement and prevents unexpected side-effects of future changes.
Definition: An object should have a single responsibility. This means that a class should only have one reason to change. An example of how this might work is with a class that compiles and formats a report. This class has two responsibilities and two reasons the class might change.
I would normally interpret this to mean that en "entity" and the validation of an entity should be separate concerns. I would normally use a single class that can validate an entire entity, but I would see no reason to constrain its implementation by not letting that class use other classes. But I would not split validation of an entity into multiple classes just because the entity has multiple attributes; I would define the responsibility of the validator as "validate entity X". Sometimes single responsibility just boils down to defining a responsibility in a clever way, and it's really about you making the rules.
Sometimes you can come across entities that have multiple valid states that may be at a different phase of a process; an order may have separate validators for separate phases, but I consider that to be a different responsibility for each validator.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With