3 ms·
I think that globals are not a problem when "you have a good [enough] understanding of the code you're writing." The problem is when code bases grow, references
by Others 7y ago
I think that globals are not a problem when "you have a good [enough] understanding of the code you're writing." The problem is when code bases grow, references to globals can start to appear in lot of different places, and the exact use of a particular one can be hard to reason about. (Strictly talking about mutable global state here.)
As code bases grow, and developers come and go, eventually no one will have a "good [enough] understanding." Mutable global state is fundamentally hard to reason about since it can be changed at any time by any part of the program. When you first start out the codebase, you can just remember where all the usages are. But eventually that is not a good approach.
I consider the testing stuff orthogonal and muddying the issue. Mutable globals are hard to reason about, therefore they can make code hard to debug. Thus they should be avoided. No need to bring testing into the picture.
- kungtotte 7y agoI think most of the problems with globals can be solved at a language level. Immutable references to globals are practically never a problem, so if your language forced you to explicitly mutably borrow a reference to a global variable you force the programmer to think about every instance of code where they are modifying the global. This also enables tooling to for example syntax highlight these things differently. An immutable global looks like any other variable, but a mutable global is bold red. You bet your ass that people will think about whether they really need it mutable in that case, and they'll know everywhere it's made mutable and therefore error prone. Again this comes back to shepherding. Globals in Rust aren't the same as globals in C++ because the languages shepherd you differently.
- amylene 7y agoRemember the old phrase, “imagine the person who maintains your code is an axe wielding murderer who has your home address”?