When dealing with POCOs, a common scenario is to track changes. Look at this interface:

namespace DirtyObjects
{
    interface IView
    {
        string Name { set;get;}
        int Weight { set;get;}
        bool Modified { set;get;}
    }
}

It is the interface of a simple view class containing the name and weight of a product. The Modified property is used to track whether the object has changed its value, so that we know if we should save the object after it has been edited.

A typical implementation might look like this:

namespace DirtyObjects
{
    class MyCumbersomeView : IView
    {
        private string name;
        private int weight;
        private bool modified = false;
 
        public int Weight
        {
            get { return weight; }
            set
            {
                if (weight != value)
                {
                    weight = value;
                    modified = true;
                }
            }
        }
 
        public string Name
        {
            get { return name; }
            set
            {
                if (name != value)
                {
                    name = value;
                    modified = true;
                }
            }
        }
 
        public bool Modified
        {
            get { return modified; }
            set { modified = value; }
        }	
    }
}

It can be seen above that modified is set to true if a change is detected whenever a setter is called. This is pretty straightforward, yet it seems that an annoying pattern emerges when there is more than a few properties.

How can we then get rid of all the boilerplate code, all the noisy bits in between? Well, there is a way: by using Castle‘s DynamicProxy and a simple technique from aspect oriented programming called method interception. Read on to see an example.
Continue reading »

© 2010 mookid on code Suffusion WordPress theme by Sayontan Sinha