IDataErrorInfo vs ValidationRule vs Exception

空扰寡人 提交于 2019-12-03 15:14:40

问题


Can anyone tell me which is a better approach for Validation in WPF.

  1. Implementing IDataErrorInfo
  2. Creating ValidationRule
  3. Throwing Exceptions

in terms of performance, memory leaks, code maintainability and re-use.


回答1:


This is kind of a complex request, and honestly it'll probably vary based on preference more than anything else. But, here's my understanding:

  • Performance: Exceptions will lose nearly every time unless your other implementations are horrendous. There's significant overhead to the throw/catch cycle. (Anecdote: I had a 'must be a number' check that was an exception, it "lagged" the UI for a noticeable time when it failed, but when converted to a ValidationRule it was effectively instant.)
  • Memory leaks: This depends on how your validation rules or IDataErrorInfo implementations are done.
  • Code maintanability, reuse: This is the interesting part, of course. What you really should be asking is "when is it appropriate to use a ValidationRule instead of IDataErrorInfo or vice versa?"

ValidationRules are older than IDataErrorInfo (I believe the latter was introduced in .Net 3.5). Based on this alone, it would seem that the WPF team prefers IDataErrorInfo. But the truth is they're built for different things. If you have MVVM or an equivalent pattern, IDataErrorInfo is superior for errors in the model (like, say, a negative age) whereas ValidationRules are superior for errors in the view (say, an age of ☃). It's of course possible to have the ValidationRules perform "business logic" checks, or to have the IDataErrorInfo tell you "a unicode snowman is not a valid age", but you'll (probably) get the best maintainability by keeping to this pattern.

But don't use exceptions for validation beyond the initial testing to see what exact conditions you should be testing for.




回答2:


It is not good idea to use exception for error handling. Using exception will reduce performance. It is a matter of selecting and Implementing IDataErrorInfo or Creating ValidationRule.

IDataErrorInfo

  • Validation logic keep in view model and easy to implement and maintain
  • Full control over all fields in the viewmodel

Validation Rule

  • Maintains the validation rule in separate class
  • Increase re-usability. For example you can implement required field validations class reuse it throughout the application.

My opinion is, for common validation like required field validations, email address validattions you can use validation rule. If you need to do custom validations like range validations , or whatever custom validation use IDataerrorinfo.



来源:https://stackoverflow.com/questions/2980853/idataerrorinfo-vs-validationrule-vs-exception

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