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

jmh530 john.michael.hall at gmail.com
Tue Jan 25 14:20:28 UTC 2022


On Tuesday, 25 January 2022 at 09:53:25 UTC, rempas wrote:
> It is known that people dislike global variables and the reason 
> is that they make the code harder to debug. In my experience 
> tho, it is the exact opposite. When I have a variable that I 
> must pass down to 5-6 functions, I find it much easier to make 
> it global rather than having it been passed in all the 
> functions that need it. [snip]

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();
}
     ```


More information about the Digitalmars-d mailing list