Monthly Archives: December 2008

Natural Born Developers

Modern software development, at least for quite a few, is all about being agile. Being agile often means that you must be able to change your code at any given time for a number of reasons; fixing bugs, achieving a better API, achieving better readability and a whole bunch of other good reasons. In order to achieve this, we try to make our code as refactorable (is this a valid word? :)) as possible. Meaning that the code is easy to change.

In addition to this, more and more developers are trying to accomplish their work through the utilization of existing patterns, or taking known patterns and modify them, or maybe even create their own patterns.

At this point, you’re probably wondering; where am I going with this? Well. Its becoming more and more obvious to me; Women are the natural born developers. They have, for instance, refactoring built into their genetics. From a very early age they will try to take some that is already there and try to improve it. Often they start with themselves, trying on different clothes to make themselves look better. At a certain point they add makeup to the mix. Refactoring themselves to a better self, for improving their interface. They continue this refactoring and when a boyfriend is introduced into their life, they start refactoring him as well. Starting again with the subtle smaller things; the clothes, moving on to haircut and adding or removing facial hairs. In addition to this, they bring the refactoring into their homes and offices in the form of redecorating or refurnishing.

When it comes to patterns, they are all into patterns. Its called fashion. They look around their surroundings and study other women from catalogues, comercials, bilboards and what not, and figure out what patterns are hip at the given time and stribe to blend into the pattern jungle.

Why is it then that computer programming is still a male dominated occupation? And are we, in the lack of women as work-mates, stribing to become women? I mean, have we been so lonely all these years that we are mimicking the womens refactoring abilities and their taste for patterns/fashion?

I will leave these questions open, as I really don’t know the answers myself. 🙂

INotifyPropertyChanged revisited

UPDATE, 12th of July 2009: Full source with sample can be downloaded from the following post

A recurring annoyance with me and quite a few other developers, is the way notification of changes from for instance your domain model to the UI should be handled in environments such as WPF or Silverlight.

The environments are heavily relying on the objects implementing INotifyPropertyChanged and hooks up to the event PropertyChanged to be notified about any changes in any properties.

This works out fine, with the exception of we as developers have to plumb in this code in all our objects.
Normally you would write something like :

[code:c#]
public class Employee : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    private string _firstName;
    public string FirstName
    {
       get { return this._firstName; }
       set
       {
          this._firstName = value;
          this.OnPropertyChanged("FirstName");
       }
    }

    private void OnPropertyChanged(string propertyName)
    {
        if( null != this.PropertyChanged )
        {
           this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}
[/code]

One can easily see that the above code can become quite boring to write over and over again. A solution could be to put the frequently used bits in a base class for all your objects. But this steals inheritance.

Another thing that bothers me with the whole INotifyPropertyChanged concept is the fact that I will be having my code filled up with literals that will not give any compiler errors if they contain typos, nor will they be subject to any renaming of properties as part of refactoring.

In my search for a better way of doing this I came across quite a few ways of trying to simplify it. The best one I came across involved using Lambda expressions to express the property that was changed and thus fixing the latter problem with renaming/refactoring. But as far as Google took me, I couldn't find anything that didn't involved switching to an extensible language like Boo or similar to really tackle the problem more elegantly. But my quest couldn't end there.

I started playing again with the problem a bit today and came up with a solution that I think is quite elegant. It involves Lambda expressions, extension methods and reflection. My three favourite things in C# and CLR these days. 🙂

Update: 16th of December 2008, thanks to Miguel Madero for pointing out the problem with value types.

[code:c#]
    public static class NotificationExtensions
    {
        public static void Notify(this PropertyChangedEventHandler eventHandler, Expression<Func<object>> expression)
        {
            if( null == eventHandler )
            {
                return;
            }
            var lambda = expression as LambdaExpression;
            MemberExpression memberExpression;
            if (lambda.Body is UnaryExpression)
            {
                var unaryExpression = lambda.Body as UnaryExpression;
                memberExpression = unaryExpression.Operand as MemberExpression;
            }
            else
            {
                memberExpression = lambda.Body as MemberExpression;
            }
            var constantExpression = memberExpression.Expression as ConstantExpression;
            var propertyInfo = memberExpression.Member as PropertyInfo;
            
            foreach (var del in eventHandler.GetInvocationList())
            {
                del.DynamicInvoke(new object[] {constantExpression.Value, new PropertyChangedEventArgs(propertyInfo.Name)});
            }
        }
   }
[/code]

When having the extension method above within reach, you will get the Notify() extension method for the PropertyChanged event in your class. The usage is then very simple. Lets revisit our Employee class again.
 
[code:c#]

public class Employee : INotifyPropertyChanged

{

    public event PropertyChangedEventHandler PropertyChanged;

    private string _firstName;

    public string FirstName

    {

       get { return this._firstName; }

       set

       {

          this._firstName = value;

          this.PropertyChanged.Notify(()=>this.FirstName);

       }

    }

}

[/code]

This is a highly reusable and pretty compact technique, and if you're not like me and aren't all that agressive with putting "this." all over the place, it will be even more compact. 🙂

Update, 16th of December 2008:

Since my original post, I also added a SubscribeToChange() extension method. The reason for this is pretty much that I literally don't like literals and wanted to have the ability to subscribe to changes for a specific property.

[code:c#]
        public static void SubscribeToChange<T>(this T objectThatNotifies, Expression<Func<object>> expression, PropertyChangedEventHandler<T> handler)
            where T : INotifyPropertyChanged
        {
            objectThatNotifies.PropertyChanged +=
                (s, e) =>
                    {
                        var lambda = expression as LambdaExpression;
                        MemberExpression memberExpression;
                        if (lambda.Body is UnaryExpression)
                        {
                            var unaryExpression = lambda.Body as UnaryExpression;
                            memberExpression = unaryExpression.Operand as MemberExpression;
                        }
                        else
                        {
                            memberExpression = lambda.Body as MemberExpression;
                        }
                        var propertyInfo = memberExpression.Member as PropertyInfo;

                        if(e.PropertyName.Equals(propertyInfo.Name))
                        {
                            handler(objectThatNotifies);
                        }
                    };
        }
[/code]

 

The above code extends classes that implements INotifyPropertyChanged and gives you a syntax like  follows for subscribing to events:

[code:c#]
myObject.SubscripeToChange(()=>myObject.SomeProperty,SomeProperty_Changed);
[/code]

 And then your handler would look like this:

[code:c#]
private void SomeProperty_Changed(MyObject myObject)
{
    /* … implement something here */
}
[/code]

Silverlight Unit Test Runner for ReSharper – new version

Its been a busy couple of months, which has put a serious break on my ability to contribute to anything but my work. But I had some hours left over and figured I'd do an update for the Silverlight Unit Test Runner for the framework made by Jeff Wilcox. It has now been updated to the latest version of the framework that is included in the December 2008 release of Silverlight Toolkit (download the source and you'll find the binaries).

The runner is pretty crude still, and has the same shortcomings as before. This is something I will address as soon as I cross the deadline barrier of the current project I'm on.

Anyhow, the binaries can be found here.

Installation notes:

  • Close any open Visual Studio 2008 instances
  • Create a directory called SilverlightUnitTestRunner in the C:Program FilesJetBrainsReSharperv4.xBinPlugins directory. If you don't have a plugins directory, create it.
  • Uncompress the ZIP file and put them in the created directory.
  • Put the Cassini.dll file in your Global Assembly Cache (open explorer, browse to c:WindowsAssembly and drag the file into here). 

Voila. You should be good to go. Your unit tests should pop up in the Unit Test Explorer and you can start running them. Mind you, that they will take a little longer to run than other tests running in the unit test explorer. This is something I will try to figure out how to optimize.

Also, if you're interested in the source code for the project, it is available here.