Why people dislike global variables so much while I find them so convenient?

rempas rempas at tutanota.com
Wed Jan 26 08:07:10 UTC 2022

On Tuesday, 25 January 2022 at 14:20:28 UTC, jmh530 wrote:
> I just made use of globals in a non-D project at work. 
> Basically, I was tasked with evaluating a few different options 
> for how to do something. There was already an existing code 
> base. For me to loop through the options at a high level would 
> require passing these variables through to multiple functions 
> and making more modifications to the code base than I had 
> wanted to. Instead, I created some globals covering the 
> different options so that I could get everything working in the 
> functions that I actually needed to change and easily test what 
> the results were with different options. When the final option 
> was decided, I removed the globals and all code associated with 
> the rejected options.
> In D, I could have used a __gshared enum* and then used static 
> if on it to switch the code paths, which would be nicer than 
> the language I was working in.
> In retrospect, an alternative could have been to create 
> separate branches and then just delete the ones that didn't 
> work out. The downside to that is that there was code that was 
> used between the different options and as I was trying things 
> out I may have changed code that all three would have used, so 
> then I would have had to update multiple branches with the 
> changes. I'm sure there is a way that git could handle that for 
> me, but it might have been a little more work. For a bigger 
> change than I was making, it might have been worth it to rely 
> on git.
> * For instance:
> ```
> import std.stdio: writeln;
> enum X {A, B, C}
> __gshared enum X x = X.B;
> void foo() {
>     static if (x == X.B)
>         writeln(x);
> }
> void main() {
>     foo();
> }
>     ```

Thank you! The thing is that this will not work on me as I want 
global variables that I will actually be able to mutate.

More information about the Digitalmars-d mailing list