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

Steven Schveighoffer schveiguy at gmail.com
Tue Jan 25 14:29:32 UTC 2022

On 1/25/22 4:53 AM, rempas wrote:
> It is known that people dislike global variables and the reason is that 
> they make the code harder to debug.

That's not the reason. Global variables are hard to control and review. 
That is, if a variable is global, how do you know it's not misused? The 
point of not using global variables is to reduce the surface area of the 
program that needs review to ensure it's correctly used.

In some cases, they make sense, and in those cases, I'd recommend at 
least guarding the direct access to the variable through properties so 
you can control how it's used.

> 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.

In D, I would do this one of 2 ways:

1. Declare the variables in a function, then run your algorithms inside 
inner functions. They all now have access to the variable. I'm surprised 
at how many complex problems and APIs become super-straightforward when 
you start using local functions (even templated ones).

2. Enclose the data and methods in a struct, even if that struct is a 
struct inside a function. This is a necessity if you have mutually 
recursive functions, since a local function cannot call another local 
function that hasn't been defined yet.


More information about the Digitalmars-d mailing list