Introduction

If you have been working with business object for a while, you may have noticed that generally, there is a lot of plumbing code to write in order to enable a fully featured BO. In this article, I’ll concentrate around the property changes notifications and how we can reduce the amount of code needed to work with those notifications. I chose this subject, because it's pretty common to find code related to it in real life applications (at least in all of that I worked on).

Using the Code

If you take a look at a property setter method within a business class, you will probably find a bunch of method calls that:

  • Notify changes to data binding infrastructure (Yes, I’m talking about INotifyPropertyChanged)
  • Mark objects as dirty, in order to know when an object had been modified
  • Keep track of properties marked as read only, to prevent unexpected modifications

Among many others that could be added to this list…. But in this case, we are going to concentrate on these very few, just because they are simple and tedious enough to probe our point.

For this sample, I wrote two classes, both have the same data structure and the same behavior for an entity called Customer. One was written in a standard way, and the other by using a feature that I call "Property Set Interception". The idea behind the code is to show the bunch of lines that we can save by using this feature.

So let’s take a look at both implementations:

As you can see in the code above, the second one is much simpler than the first one, but what I’m saying is that both behave in the same way, so how is this possible?

Simple, in the second one, we just intercept all messages (method calls) executed on our object, and if it’s a property setter method call, we handle all notifications tasks in the one place for all properties, which means that the code is written just once for all of our business objects. By doing that, we can save a lot of coding time and maintenance effort.

In this case, I wrote a console app that prints out all of the actions performed by the business objects just to probe that both implementations behave in the same way.

The interception mechanism might be a little complex, but if you just want the highlights, you can place breakpoints at the methods listed down below and see how it works.

So, where is the catch?

Well, this feature will probably be a package deal with debug complexity. So you shouldn’t try it in production environments, at least not until you’re sure that has been tested enough in a couple of development cycles. I make an advice on that, because you may end up spending much more time during debugging sessions, than the time you have saved during the coding process. Check your scenario very carefully and make your own conclusion.

As always, comments are more than welcome.

History

  • 8th April, 2011: Initial post
  • 10th April, 2011: Article updated
推荐.NET配套的通用数据层ORM框架:CYQ.Data 通用数据层框架
新浪微博粉丝精灵,刷粉丝、刷评论、刷转发、企业商家微博营销必备工具"