单一职责原则对于验证意味着什么
单一责任原则是否意味着您的验证规则应该位于实体外部?
如果是这样,您是否为每个验证规则使用一个类?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我通常将其解释为“实体”和实体的验证应该是单独的问题。 我通常会使用可以验证整个实体的单个类,但我认为没有理由通过不允许该类使用其他类来限制其实现。 但我不会仅仅因为实体具有多个属性而将实体的验证拆分为多个类; 我将验证者的职责定义为“验证实体 X”。 有时,单一责任归结为以巧妙的方式定义责任,而这实际上是关于你制定规则的。
有时,您可能会遇到具有多个有效状态的实体,这些状态可能处于流程的不同阶段; 订单可能有不同阶段的单独验证者,但我认为每个验证者都有不同的责任。
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.
取决于您对实体的定义。 例如,您可以验证每个服务层中的输入,但此验证可能由单独的类处理。
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.