Thursday 28 January 2010

Starting Listeners in the Correct State

A problem that I'm having with event listeners at the moment is making the listening object begin at a point in time in the correct state when it is really designed to build its state from the the events that are received while assuming a state to begin with.

For example, say you add a listener to an observable containing the state for a light switch, the listener should really know the state straight away but the event could be fired in 8 hours, or never. There are two ways I can see to fix this.

When adding the listener the listener gets the current state from the observable and updates itself.  This is fine but it does mean that the listener needs to know about the observable which adds a dependency so that the listening object is less reusable.  The Java property change framework is weakly typed, treating sources and values as objects anyway so you shouldn't really be expected to add this dependency.  Plus it makes the listener more difficult to test.

The observable holds a copy of the last event object it fired and when a listener is added fires all events to that listener.  This can give us even more problems.  Imagine firing an event with a complex or resource hungry value.  The complex object could have references to many other objects that would get garbage collected except that this stored event keeps them in memory.  An image is probably the best example of an object that you wouldn't like to keep in memory longer than necessary.  This really means that only primitive values, enums and other small immutables should be the values in change events.

These problems are really compounded for state machines where to get begin at the correct state the machine has to analyse system state in much the same way a conventional solution would need to.

No comments: