IDataErrorInfo vs ValidationRule vs Exception

2019-04-03 15:49发布

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.

2条回答
走好不送
2楼-- · 2019-04-03 16:41

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.

查看更多
爷、活的狠高调
3楼-- · 2019-04-03 16:53

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.

查看更多
登录 后发表回答