Design Patterns – How is the Publish-Subscribe Pattern Different from Gotos?

design-patternsevent-programmingpubsub

My understanding is that Goto statements are generally frowned upon. But the publish-subscribe pattern seems to be conceptually similar in that when a piece of code publishes a message, it performs a one-way transfer of control. The programmer may have no idea what parts of the program are subscribing to this message.

I have see something similar in a lot of JavaScript programs in which events are used to conveniently "hop" across modules. Am I missing something about the publish-subscribe or event-driven patterns?

Best Answer

Yep, you are definitely missing something. Gotos would typically be used, like you said, to perform a one-way transfer of control.

However, events do not do that. When the code fires the event, it knows full well that once event is published (or processed, queued, fired... etc) code execution will resume on the very next line in the code that generated the event.

The use of goto creates a very tight coupling between the code that calls that statement and the code that's on the receiving end. Developer has to have intimate knowledge of both places in order to use goto.

On the other hand, code that fires events would typically not know or care who is interested in listening for that event. There could be a listener. Or there could be a 100 listeners or 0. Those listeners could be in the same program where event was fired, or they could be in a completely different application, or they could be on a different machine. As far as the publisher is concerned, as soon as he generates the event his job is done.

If you are with me so far, what I described above is the ideal case of pub/sub pattern. Unfortunately in the real world things aren't always ideal and there are cases where publishers generates an event, a subscriber gets invoked, changes a whole bunch of state and by the time code execution returns back to the publisher "the world" appears to have been turned upside down. And I'm sure you've run into this in the past, because this condition often arises when pub/sub pattern is implemented in a very simple fashion (e.g. via use of delegates or events in C#, or function/interface pointers in C/C++).

But this problem isn't necessarily pub/sub pattern but rather the implementation of it. This is why many systems rely on queues so that when an event is published, it is simply queued up to be invoked later giving the publisher a chance to finish execution while the world is still intact. When publisher is done doing it's work, an event loop (aka dispatch loop) will pop off the events and invoke subscribers.

Related Topic