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

H. S. Teoh hsteoh at quickfur.ath.cx
Wed Jan 26 23:40:48 UTC 2022


On Wed, Jan 26, 2022 at 11:13:56PM +0000, MrJay via Digitalmars-d wrote:
[...]
> a lot of code practices people recommend such as not using macros is
> because of team environments' because many convenient code practices
> can easily cause confusion for your peers. but I still dont understand
> why people see it as a sin of coding to use global variables, it
> depends on the code base and the project.
[...]

I don't consider it a "sin" to use global variables, I've done that
myself in the past (and still do it occasionally for one-off scripts,
because let's face it, it's darned convenient).  Only thing is, in
pretty much every non-trivial project where I've used globals, I ended
up regretting it later because of the myriad of problems associated with
using global variables. Such as not being able to create new instances
without rewriting a ton of code (e.g., the database connection example
in my other post), being confusing to debug (some global changed between
the call to f() and the call to g(), but it's totally non-obvious from
reading the code and left me scratching my head as to why g() is
suddenly behaving funny).

This applies not only in team environments -- in single-person projects
the "confused team member" could very well be yourself after 3 months
("WHAT I was thinking when I wrote this?!"). Or, in my case, 5 years
("WHAT was I trying to do when I wrote this crock?!").

After many experiences of this, I've come to the conclusion that the
convenience of using globals is usually not worth the trouble they cause
down the road. I rather "waste" a bit more time writing things the
"right" way now, than to waste a LOT of time (and frustration) later
trying to debug code riddled with global state.


T

-- 
It said to install Windows 2000 or better, so I installed Linux instead.


More information about the Digitalmars-d mailing list