Wednesday, June 22, 2011

Getting rid of Literal strings - part 1

In my travels around MVVM Land (specially as seen on MSFT tutorials around the net), it is commonplace to find string literals being used when implementing the , to specify the property name (as shown in the code below).

  1:     public class Customer : INotifyPropertyChanged
  2:     {
  3:         private string _firstName;
  4: 
  5:         public string FirstName
  6:         {
  7:             get { return _firstName; }
  8: 
  9:             set
 10:             {
 11:                 _firstName = value;
 12:                 PropertyChanged(this, new PropertyChangedEventArgs("FirstName"));
 13:             }
 14:         }
 15: 
 16:         #region INotifyPropertyChanged Members
 17: 
 18:         public event PropertyChangedEventHandler PropertyChanged;
 19: 
 20:         #endregion
 21:     }



But excessive use of the Copy + Paste “design pattern”, can be error prone – often times when Copying + Pasting, I forget to change the string to the new property name, and/or misspell the intended name - causing your ViewModels not to work correctly.



Solution: The guys at Microsoft Patterns & Practices  have included some nice "lifestyle enhancing” features in Prism that make your everyday coding much enjoyable. One of those features is the NotificationObject, an abstract class that implements the INotifyPropertyChanged (INPC) interface, and allows you to write code such as this:



  1: public class Customer : NotificationObject
  2:     {
  3:         private string _firstName;
  4: 
  5:         public string FirstName
  6:         {
  7:             get { return _firstName; }
  8: 
  9:             set
 10:             {
 11:                 _firstName = value;
 12:                 RaisePropertyChanged(() => FirstName);
 13:             }
 14:         }
 15:     }


Notice that Line 12 does not use a “Magic String”, but rather a lambda expression that points to the property. This gives you compile-time checking as well as refactoring with ease. some improvements could be  made (i.e.: Only raising the Property Changed event when the value changes), but I will leave that up to you.