Rob Smyth

Wednesday 15 August 2007

When To Use .Net Events

I've been a long fan of .Net events and have had great success with them. I like an event driven model. But recently I've been wrestling with code in which events seem to cause more complications than they solve. Today in discussion with colleagues about implementation of undo/redo in an application the penny dropped. Using events within presentation layers is good but not in domain (model) objects as they greatly complicate object persistence.

The undo/redo is a great example, if an object that is being deleted has subscriptions to events on other objects and the subscriptions are deleted how do you restore the object? If you do not delete them then your inactive object is now being modified by events from the still active objects. Besides, is it a code smell if domain objects are notifying each other of changes? Does that imply poor encapsulation?

It seems to be lifetime issue. UI components typically sit in a child-parent relationship were all are created and discarded together so the need to manage event removal is not as critical.

No comments: