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

rempas rempas at tutanota.com
Tue Jan 25 11:37:54 UTC 2022

On Tuesday, 25 January 2022 at 10:22:17 UTC, Ola Fosheim Grøstad 
> Harder to debug


> Harder to reason about as your program grows

What does this mean? No, I'm not joking, I truly don't get it. Do 
you mean "reason" as the reason they exist and what they do?

> Harder to scale your program to higher degree of concurrency

Why? What's the difference between having a variable in a global 
space vs passing a pointer and having to difference it when it 
comes to concurrency? In both cases, you need to check if what 
you are trying to use is already in use (unless you don't care, 

> If you use globals you should keep them local to one 
> object-file and limit access to accessor functions to make it 
> easier to debug your code.

I mean, if you keep them local to an object file that they lose 
their bigger advantage. How many functions will be in this file 
compared to the whole project? So we don't win much.

> If you only use globals because you want to have fewer 
> parameters then the common approach is to instead use a 
> context-object and pass that as single parameter.

Yeah but in that case, I will have to create an object and use 
pointers. And also use a pointer for this object and have to 
dereference it every time. So yeah, the runtime performance will 
not be happy about that...

> Unfortunately, D made the mistake of making thread-local the 
> default, and claimed this was a great improvement. Thread local 
> globals are basically something you only want to use in runtime 
> and framework "kernel" like code. That gets you an additional 
> layer of issues, including performance.
> If you use globals, make sure you either mark them 
> appropriately so that you don't get thread local globals.

How can I do that?

More information about the Digitalmars-d mailing list