Why people dislike global variables so much while I find them so convenient?
rempas
rempas at tutanota.com
Wed Jan 26 11:22:55 UTC 2022
On Tuesday, 25 January 2022 at 21:34:57 UTC, Dukc wrote:
> 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.
Yeah, of course. In your example, it is actually stupid to use a
global variable and it doesn't makes sense.
> 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.
Yep, like other said! I'm doing that right now! Thanks!
More information about the Digitalmars-d
mailing list