by krab · 5y ago · 0 comments
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.
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.