Why people dislike global variables so much while I find them so convenient?
jj_1337 at live.dk
Tue Jan 25 10:18:50 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. In my experience
> tho, it is the exact opposite. When I have a variable that I
> must pass down to 5-6 functions, I find it much easier to make
> it global rather than having it been passed in all the
> functions that need it. This practice also makes my function
> signatures looking much cleaner. Yeah, one variable will not
> make a difference but in my project, I have about 2-3 variables
> that need to be passed down to a lot of functions so I only
> think that it makes sense to use them as globals. Another
> problem is the case that I'll introduce a new variable that
> needs to also be passed in most of my functions. What happens
> then? Let's say I will have 20 functions at the time. I have to
> change both the function signature and all the other places in
> code that call this function. The latter can be easily done
> with a quick "search and replace" in my text editor but still,
> it's a tedious thing to do.
> So can someone make examples about how global variables can
> mess me up. I know that probably everyone here has more
> personal experience than me so I really want to learn why
> global variables are considered so harmful.
The problem with globals is that anyone and anything can modify
It becomes especially problematic when your program receives
input from elsewhere such as connections like sockets, http etc.
or even other threads.
In my opinion globals are fine IFF they're only initialized once
(and only one place is allowed to modify them) and/or they're
Globals are extremely convenient to use and that's also why
they're extremely dangerous to use.
More information about the Digitalmars-d