开发者

Should I place validation code in domain model or keep it external?

I am working on some user registration code, and I'm wondering where the best place is to put my validation code. I can create a user validation object and pass the user model to it to validate, or I can just instantiate the validation obj开发者_JS百科ect within the user model or even write the validation code into the user model, however, I'm thinking that this would be wasteful as the validation object/code is only used when registering, and editing user data. Therefore, I'm leaning to keeping the user validation object external. Can someone advise me as to what the best practices are? Appreciate your help!


Generally speaking, I'd say make the User model responsible for maintaining its own validity. Put these invariants in the model itself. Then, nothing can put a User in an invalid state, not just your current creation and editing features.


I've usually kept my validation code separate from my model code in an MVC application. Essentially all my models assume that data passed into them is already clean/correct. This allows for more readable model code, and more centralization/reuse of validation code.


I tend to keep the validation code separate from the model. In fact, it is more related to the code of the interface.

When you create the model you cannot be sure for the interface. Maybe you will have 2 or more forms that manipulate data of a single object:

                                    ---------
                                    | Form1 |
---------       -------------   /   ---------
| model |   -   | Validator |
---------       -------------   \   ---------
                                    | Form2 |
                                    ---------

If the validator is bound to the model, you cannot support multiple forms. Suppose that you had one validator for both forms. Then you could end up with some really funny messages. For example, "The field X is mandatory" and have the user wonder where on earth field X is. (Field X is in the other form...)

So, this solution is better, from this point of view:

                --------------     ---------
                | Validator1 |  -  | Form1 |
---------  /    --------------     ---------
| model |  
---------  \    --------------     ---------
                | Validator2 |  -  | Form2 |
                --------------     ---------
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜