Tutorial :What does the single responsibility principle mean for validation



Question:

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?


Solution:1

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.


Solution:2

Depends on your definition of entity. You can, for instance, validate input in every service layer but this validation might be handled by separate classes.


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »