Why people dislike global variables so much while I find them so convenient?
bachmeier
no at spam.net
Tue Jan 25 14:44:01 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.
I object to your question. There's not necessarily anything wrong
with global variables, for loops, goto statements, and whatever
else some claim you shouldn't use. Maybe you're thinking of
Haskell.
I don't think it's common that you need global variables in D. If
you want to share a variable among several functions, use a
struct. But if a global is the best solution, use the global.
If you've ever had the joy of working with FORTRAN 77 or earlier
versions of FORTRAN (back when it was in all caps) you understand
why working with globals can be a traumatic experience. For
instance, multiple functions in multiple files will sometimes
change the same global variable.
You have global variable x. foo calls bar which calls baz which
changes x. Then 75 lines later foo calls goo, which also changes
x. Even if there's no bug in your code, this style of programming
will burn threw all your brain energy in a hurry. You have to
think about the entire program in order to reason about one part.
It was often easier to rewrite the whole thing from scratch than
to make a meaningful change involving global variables.
More information about the Digitalmars-d
mailing list