What does the single responsibility principle mean for validation

梦想与她 提交于 2019-12-01 02:02:10

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!