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

Dukc ajieskola at gmail.com
Tue Jan 25 21:34:57 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.

Assuming you mean mutable global state. Immutable global data is 
okay IMO.

Because purity is convenient. When I call a function, let's say 
`field.initializeUnit(12, 15)` it's so much nicer and tidier if I 
can rest assured it won't affect anything else than `field`, and 
if I know it acts the exact same way every time, when the 
arguments are similar.

Now consider if `field` was a global variable. Okay, 
`initializeUnit(12, 15)` is shorter than 
`field.initializeUnit(12, 15)`. But I have to set the field I 
want to manipulate in advance, `theField = /*whatever*/`. And 
when reading code that acts like this, I do not know what affects 
what without peeking what each of the called functions do. Did 
the `initializeUnit` use `theField` or `thatOtherField`? With the 
pure version I can instantly see it's the `field` variable I'm 
using. The non-pure version is much uglier and harder to read 
after all, despite having a shorter argument list.

If the argument lists get lengthy, it is sometimes worth to 
collect the argument sets into structs or classes that have most 
of the needed data in one place. You might also consider the 
`with` statement. But globals just plain blow.



More information about the Digitalmars-d mailing list