Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
749 views
in Technique[技术] by (71.8m points)

wpf - IDataErrorInfo vs ValidationRule vs Exception

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...