“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
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.
2