Alex Rivera | Logout

Why people use message/event buses in their code?

Asked 2010-10-21T12:25:40.817
60

I think that you have heard of message/event buses, it's the single place when all events in the system flow. Similar architectures are found in computer's motherboards and LAN networks. It's a good approach for motherboards and networks as it reduces the number of wires, but is it good for software development? We don't have such restrictions as electronics does.

The simplest implementation of message bus/event bus can be like:

class EventBus {
    void addListener(EventBusListener l}{...}
    void fireEvent(Event e) {...}
}

Posting events is done with bus.fireEvent(event), receiving messages is enabled by bus.addListener(listener). Such architectures are sometimes used for software development, for example MVP4G implements similar message bus for GWT.

Active projects:

Dormant/Dead projects:

It's just the popular Observer (Listener) pattern made 'globally' - each object in the system can listen to each message, and I think it's bad, it breaks the Encapsulation principle (each object kno

Edit
Report

1 Answer

16

I use it heavily in JavaScript. There can be so many various widgets that all need to do some sort of action whenever something else happens -- there is no real hierarchy of ownership of objects. Instead of passing references of every object to every object, or just making every object global, when something significant happens inside a particular widget, I can just publish "/thisWidget/somethingHappened" -- instead of filling that widget with all kinds of code specific to the API of other widgets. The I have a single class that contains all the "wiring", or "plubming" as they like to call it in the Java Spring framework. This class contains references to all of my widgets, and has all of the code for what happens after each various event fires.

It is centralized, easy to access and maintain, and if one thing changes or I want a new process to occur on a specific event, I don't have to search through every single class/object/widget to try to find out where something is being handled. I can just go to my "operator" class -- the one that handles all the "wiring" when a particular event happens, and see every repercussion of that event. In this system, every individual widget is completely API agnostic of the other widgets. It simply publishes what has happened to it or what it is doing.

answered 2010-10-21T15:01:09.397

Your Answer