问题
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?
回答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.
回答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.
来源:https://stackoverflow.com/questions/865144/what-does-the-single-responsibility-principle-mean-for-validation