"Minimize mutable global state" is a more or less accepted program design principle. The reason often cited is that having global state can affect two components that don't are seemingly unrelated. In other words, a component mutating global state would have no idea who else it is effecting since it doesn't know what other component has a dependency on that global state.

Tangentially, a pattern that is often recommended for building decoupled software is the event bus pattern where a component capable of generating events broadcasts it over a bus and components interested in certain events subscribe on the same bus to receive said events.

My question is - doesn't the argument that holds for global state hold in the case of event bus too? After all, when broadcasting an event, I have no idea who else I am breaking since I have no way to know what other components are listening for it. Further, just as in the case with global state, reading the code might not make the dependencies of components on a certain even clear at the site of broadcast either.

The only difference between the two that I can think of is that an event is a transient state versus global state in the form of static variables or shared objects, that might be persistent.

  • 1
    an event bus makes the relation ship between the components (event emitter and consumer) explicit during registration – ratchet freak Aug 13 '14 at 11:14

Yes, it's global state, but it's appropriately controlled global state. With the event bus, a given receiver can usually register for just the events it wants to see, and a given sender will only send a very small selection of the possible events. The ordering of event handling is often in some way defined by the event bus (as opposed to everyone polling a global willy-nilly). In an event bus, the only way things change is if everyone gets NOTIFIED that they changed.

Your problem is that you're taking the idea 'global state==bad' too literally. Unmanaged global state is bad. Global state that can change without notice is bad. Well controlled, properly isolated global state lets you get the job done.

  • +1. A program that doesn't modify any global state effectively does nothing, and can probably be optimized by a clever enough compiler to an empty executable. – Haspemulator Aug 13 '14 at 12:21
  • Not if the program returns some return code that is dependent on a calculation – Charles Salvia Aug 13 '14 at 18:01

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.