Skip Navigation LinksHome > View Post

How to work with PropertyChanged's smelly name string

Karl posted an interesting article recently INotifyPropertyChanged – How to remove the Property Name String Code Smell.

It'a nice implementation and the resulting code certainly looks a whole better. As Karl notes the biggest problem this approach faces is one with performance.

Notably, the proposed implementation is a lot slower when there are listeners wired up to the INotifyPropertyChanged plumbing.

The performance could be improved by caching the StackTrace based on an accompanying static key for each property, e.g.

private static readonly object _namePropertyKey = new object();

public string Name
{
    get { return _name; }
    set
    {
        _name = value;
        OnPropertyChanged(_namePropertyKey);
    }
}

However, this is probably just as prone to runtime errors in case somebody uses the wrong key with the wrong property.

With respect to the importance of performance then Karl is right to note that your users can only type so fast. But in some models and viewmodels, say containing a few hundred points that will be represented on a chart. That hit in performance could REALLY hurt.

My approach to this problem is to leave the smelly string where it is and automate the testing process using the Automatic Class Tester. This will automaticaly test that your properties are wired up appropriately and, if your class implements INotifyPropertyChanged it will also check that the appropriate PropertyChanged string name is fired.

 
Josh Post By Josh Twist
10:52 AM
02 Aug 2009

» Next Post: A Suck Less Event Aggregator for Prism?
« Previous Post: Silverlight, Validation and MVVM - Part II

Comments are closed for this post.

Posted by Pieter @ 02 Aug 2009 1:45 PM
How about using PostSharp to auto implement OnPropertyChanged for you?

Posted by Krzysztof Kozmic @ 02 Aug 2009 1:47 PM
Or,

you can do what everyone seems to be doing, make your properties virtual and use Castle Dynamic Proxy... or PostSharp

Posted by Rod @ 18 May 2010 8:05 PM
Sorry Josh, but the link to karl's blog is broken... because it was moved from one day to another... Could you please update your post to

http://karlshifflett.wordpress.com/2009/08/02/inotifypropertychanged-how-to-remove-the-property-name-string-code-smell/

:P

Posted by Josh @ 19 May 2010 4:43 AM
Done, thanks Rod.

© 2005 - 2014 Josh Twist - All Rights Reserved.