When dealing with POCOs, a common scenario is to track changes. Look at this interface:
1 2 3 4 5 6 7 8 9 |
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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 |
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.
Read more