7

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?

rjzii
  • 14,236
  • 12
  • 79
  • 119
Dug
  • 825
  • 1
  • 9
  • 19

2 Answers2

3

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.

krosenvold
  • 75,535
  • 32
  • 152
  • 208
1

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.

Mehrdad Afshari
  • 414,610
  • 91
  • 852
  • 789