3 ms·
I agree that globals are usually a bad pattern, but there are situations where judicious of globals is warranted and can actually improve readability. An examp
by speleding 7y ago
I agree that globals are usually a bad pattern, but there are situations where judicious of globals is warranted and can actually improve readability.
An example is small scripts, where the scope of the script limits the scope of the global. The overhead of an abstraction doesn't pay off in that case.
Another example are "near constants" like a locale setting, an environment variable that gets detected once at startup, or a development feature flag. The "proper" way to structure those is to create a settings object and pass it to every function that needs them, but judicious use of a well-documented global can prevent a lot of boiler plate code.
Of course, as soon as the code base needs to be touched by many devs, especially less experienced ones, it's safer to say "never do it" than "judiciously use", so I understand why most textbooks say this.
- clarry 7y ago> Another example are "near constants" like a locale setting, an environment variable that gets detected once at startup, or a development feature flag. The "proper" way to structure those is to create a settings object and pass it to every function that needs them, but judicious use of a well-documented global can prevent a lot of boiler plate code. In small programs, globals are ok, but in larger programs a better approach would be a global accessor that gives you read-only access: printf("%s\n", Environment()->Host); This doesn't require passing an object to every function, and the application still can't trample on these variables.