[英]Where do you place your validation logic?
How would you structure your code in the following scenario: 在以下场景中,您将如何构建代码:
Several business objects (egPerson, House, etc), and between them, you need to validate the user inputs (which come in from textboxes). 几个业务对象(例如,People,House等),在它们之间,您需要验证用户输入(来自文本框)。 Would that go in either: 会是这样的:
Thanks 谢谢
A very widely used approach, which I endorse in such scenarios, is to introduce the concept of a viewmodel: a class that aggregates all data to be displayed in a form, and which specifies (through attributes or some other mechanism) what type of validation should be performed on this data. 我在这种情况下认可的一种非常广泛使用的方法是引入视图模型的概念:聚合所有要在表单中显示的数据的类,并指定(通过属性或其他机制)什么类型的验证应该对这些数据进行处理。
This approach has several benefits which include: 这种方法有几个好处,包括:
The actual code that does the validation will typically be inside a separate validation class; 执行验证的实际代码通常位于单独的验证类中; your viewmodel would only dictate how each piece of validation should apply to each piece of data. 您的viewmodel只会指示每个验证应如何应用于每个数据。
Each business object. 每个业务对象。 I have classically made each one implement an IValidator interface that spits out all validation errors for the object. 我经典地让每个人实现一个IValidator接口,该接口为对象吐出所有验证错误。
In the business objects . 在业务对象中 。 The reason is that you would like your validation rules to be testable. 原因是您希望验证规则可以测试。 If the rules are important you will want to cover them with tests, if they are not - Don't implement them in the first place. 如果规则很重要,你会想要用测试来覆盖它们,如果它们不是 - 不要首先实现它们。 Taking this to the extreme gives you code where the codebehind is extremely thin and does hardly have any logic in them. 将这种情况发挥到极致可以为代码提供极其薄弱的代码,并且几乎没有任何逻辑。 This is something to desire. 这是需要的东西。
Some good practise here: http://colinjack.blogspot.com/2008/03/domain-model-validation.html 这里有一些好的做法: http : //colinjack.blogspot.com/2008/03/domain-model-validation.html
Once in place, in the domain model, the UI should be able to reflect the validation state/output from the model. 一旦到位,在域模型中,UI应该能够反映模型的验证状态/输出。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.