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

MrJay mrjcraft2021 at gmail.com
Wed Jan 26 23:13:56 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.

when you create a global variable anything can modify it, meaning 
that if someone else writes code, or another thread changes the 
variable, it can cause side affects, and it can be difficult to 
follow especially because you may not know what or where the bug 
is, also when you pass it into a function then you are 
effectively documenting the code, this means in the future it 
will be much easier to debug because you know where it is going, 
especially when working in a team environment. however this is 
yes good practice but I still use global variables when it is 
convenient for a smaller project where the code fits on one 
screen, or the name of the variable describes its location. but I 
work for myself and I am the only one who sees my code.
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.

In some of my code there is only global variables because one of 
the languages I use only uses global variables so if something is 
broken it takes a hot minute, I dont know what function is 
causing the error, just have to go through them all.


More information about the Digitalmars-d mailing list