Observers shouldn’t observe themselves
I’ll say this as clearly as possible: observers shouldn’t observe themselves. An event indicates that something of importance will occur or has occurred. There is some default behavior that is of interest to observers and the event is the way to broadcast that this important moment in processing has occurred. The default behavior should never be executed by an observer. Let me state this as a concrete example: if your object publishes a load event, you shouldn’t assign an event handler that does the loading. The default behavior should be there regardless of the event. In fact, you should be able to remove all events and have the object still perform its duties appropriately.
Again, I love the observer pattern and I’m a big fan of creating objects with custom events (loosely coupled objects rule!). But let’s have some sanity around events. Let the important moments be just those, and make sure your object works appropriately without any observers subscribing to its events.
Disclaimer: Any viewpoints and opinions expressed in this article are those of Nicholas C. Zakas and do not, in any way, reflect those of my employer, my colleagues, Wrox Publishing, O'Reilly Publishing, or anyone else. I speak only for myself, not for them.
Both comments and pings are currently closed.