3 ms·
If you're careful global state is useful. It provides a sort of tele-interface - tunneling a value from the top level scope to the bottom where it is used. Ima
by krab 6y ago
If you're careful global state is useful. It provides a sort of tele-interface - tunneling a value from the top level scope to the bottom where it is used.
Imagine a larger CLI application. You get all of the command line flags at once at the beginning, but some of them are used at the bottom of the implementation. Passing them all across all the layers gets tedious so you would invent some sort of "context" object passed through your functions. Another example is Flask's global request object.
If done correctly, it may be much cleaner than passing the values through the stack. You must not overuse it and you have to think about thread safety. It's useful to ensure the values are set once and then they're immutable to avoid surprises, and you must ensure the global value is cleaned when no longer valid.
- kortex 6y agoOf course global state is useful. All interactions with the universe (all i/o, anything with time) involve global state. So what makes DB's a smart pattern but global variables usually bad? It gets hairy whenever you have "behind your back" mutation within a single scope. Because db calls are costly, people usually batch the transaction and pass the result to mostly pure functions. If you were to do something silly like wrap a Redis get/set in a Mapping, it'd feel an awful lot like a global dict. This is why things like transactions, event sourcing, and the reactor pattern exist. You batch all i/o to the global state so you a) deal with immutable structures everywhere else b) have ACID c) have traceability.
- krab 6y agoYes. And also transactions are interesting because of their explicit nature. Including STM. They lead you to think at least a bit about all the concurrent traffic.