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.
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 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.