You may notice a couple of key differences here, and they will have an impact on our application. The differences can be extremely subtle. In the first example we execute an action when our Email
property is updated. In the second we have no action executed but we call OnPropertyChanged
for the IsValid
property anytime the Email
property is updated. What does all of this mean?
I fully admit I really like the syntax of the second refactoring, it is far more elegant. That said, there is a particular problem that we would face using this syntax. Take the email '
[email protected]', and say that the Email field is bound to an Entry field. When the user types 'j'
OnPropertyChanged
is called for the
Email
property and
IsValid
property. The user types 'o', again
OnPropertyChanged
is called for both properties. This would continue for every single character meaning that the UI would have to respond to the event for both bindings.
Now say that you use the first implementation where you call the action
OnEmailChanged
when the
Email
property is changed, and this then executes
IsValid = RegEx.IsMatch( Email, AppSettings.EmailRegExPattern )
. What we are really doing is checking to see if anything has really changed. Again saying that the user types 'j', the action attempts to set a value of 'false' for
IsValid
. Since the property already was false,
OnPropertyChanged
is never called and the UI never has to respond to it. In fact the user would have to have entered
[email protected]
before we would see
OnPropertyChanged
being executed for the
IsValid
property. Another way of putting it that we would have been telling the UI to do something 17 times, taking up CPU time that was never needed. Then we would notify the UI again when the user typed the final character.
By using a helper like Fody, we can instead write clean concise code, following the best coding practice that fits our exact situation.