Why is it so bad to use global variables? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 18

Why is it so bad to use global variables?

I mean everyone is trying to find a way to not use global variables. The foundation of static variables is an example of this if i have understood them right.

21st Oct 2019, 6:47 AM
Emad
40 Answers
+ 40
If your code is thousands of lines long and you use global variables and something goes wrong, you'll have no idea where the mistake is: Every part of your code has access to these values, so the mistake could be literally everywhere. By strictly sticking to small scopes, like local variables in a function, you can figure out each function by itself without even looking at the rest.
21st Oct 2019, 6:58 AM
HonFu
HonFu - avatar
+ 18
Mirielle🐶 [Inactive], I am honestly surprised that you see this for the first time, since it is very common - not really depending on any language. This is not about simple exceptions like a type error or something. If every function has access to a variable, it can *change* the variable! Data gets modified, but the program runs on, and you look at the mess and ask yourself: What's going on? What do you think scopes, namespaces, encapsulation, privacy and all of that are for?
21st Oct 2019, 7:44 AM
HonFu
HonFu - avatar
+ 14
[Part 2 of 5] Newt Austin I was shocked to see that paper was from a professor of computer science. He has obviously not written much commercial quality code that has increased in complexity over time and tried to figure out why the state of a global variable was intermittently storing the wrong value in various scenarios and conditions? He's obviously not had to refactor code with tightly coupled dependencies on global variables only to find new unexpected behaviors to later emerge. He's obviously never written unit tests or attempted to debug multi-threaded processes to isolate inconsistent results and behaviors due to global variables. He's obviously not worked with systems that will load modules and their variables into the global scope causing real name collisions. He obviously doesn't understand the value of namespaces over global variables. His references and comparisons to OOP reflect that of a beginner student in an intro to CS course.
22nd Oct 2019, 1:49 AM
David Carroll
David Carroll - avatar
+ 12
[Part 3 of 5] Newt Austin While OOP languages do support different variable scope levels like static and instance class fields; and function and block scoped variables; OOP still falls short in enforcing immutable state and pure functions with no external side effects. This would have been a valid argument had the professor understood what he was writing about. However, the impact of this shortcoming in OOP is reduced by an order of magnitude compared to that of similar code making liberal use of the global scope. This is where pure functional languages shine as variables are immutable and functions do not cause any external side effects. I can only imagine how entertaining the paper would have been had the professor attempted to make his case using functional programming references instead of OOP.
22nd Oct 2019, 2:08 AM
David Carroll
David Carroll - avatar
+ 11
Mirielle🐶 [Inactive], concentrate. Humans write programs, and humans make mistakes, especially when the programs get long and complicated. Programmers may *accidentally* 'allow' the program to increment or decrement that value, without even knowing! By limiting the accessibility of values, you reduce the scope of disaster - and the number of places you have to check if you mess something up anyway. I am sure this topic has come up in your CS course!
21st Oct 2019, 1:35 PM
HonFu
HonFu - avatar
+ 10
Mirielle🐶 [Inactive], of course you can write your own code whichever way you like and only use global variables. You can also decide not to use any classes or functions and decide to write spaghetti code that indents 30 levels deep - go for it. But you should know that this is not the way it's regularly done. If this was the way to do it, we would probably write a lot less functions, and OOP would have never been invented. Global variables is something you avoid and in some cases use... unhappily... because other choices might be bothersome or whatever, but not something you recommend as the standard. Google 'global variables bad' or something like that, and read up on it. Just to get an overview. After that, you can still do it whichever way you like.
21st Oct 2019, 2:01 PM
HonFu
HonFu - avatar
+ 10
[Part 1 of 5] Emad I can imagine the confusion on why it's discouraged to use global variables from the perspective of new programmers or even those with limited exposure to code bases beyond a few hundreds lines. Thanks ✳AsterisK✳ for digging up that explanation I posted. I'm not sure I would have found it myself. 😉 Hopefully my nested reply in that thread will make sense on why global variables should be avoided on larger code bases.
22nd Oct 2019, 1:38 AM
David Carroll
David Carroll - avatar
+ 9
Mireille, you mainly think of errors that can be seen by an error message. (Syntax error, ValueError or what ever). But what about if some part of your code just do an increment or decrement of a variable, or simply assigned a True or False by accident. This is what happens, and believe me this is one of the hardest part of coding to figure out what happens. To use local variables with a small scope, or using oop with encapsulation can prevent a lot of trouble in coding.
21st Oct 2019, 10:30 AM
Lothar
Lothar - avatar
+ 9
ohoho you dont want to know how many games i've cheated because they use global variable to handle important variables. i'm talking about javascript games btw.
21st Oct 2019, 8:43 PM
Taste
Taste - avatar
+ 9
David Carroll it was actually ✳AsterisK✳ who dug up that link. [Edited by David Carroll] DOH... Thanks... I corrected my post. 🙏
22nd Oct 2019, 2:34 AM
Sonic
Sonic - avatar
+ 9
[Part 4 of 5] Emad Regarding your question about static variables being used as an alternative to global variables... Not at all. Static members are bound to a namespace which includes the class type. Example: SomeApp.Thing.Config.ConnString Global variables are accessible simply by the symbol name alone. Example: connString A variable isn't global because it's accessible throughout the lifetime of the application process. Rather, a variable is global because it's accessible by name only from anywhere throughout the application.
22nd Oct 2019, 2:40 AM
David Carroll
David Carroll - avatar
+ 8
Newt Austin, I would have enjoyed to hear more from that prof about how globals are needed in parallel programming etc. Unfortunately he had to waste 75% of his paper attacking a straw man. It makes sense to tell beginners that stuff, that doesn't need to be shared, should not be global. Of course there'll be situations where globals make sense, but that's a far cry from using them indiscriminately and everywhere. He gives his fictive enemy the name anti-globalists and calls them hypocrites. But in the end, in one sentence, he tells the truth: The scope is different. Seriously? He compares global state with instance state? 🤔 Look at most of our codes here, a few hundred lines long. If there are a few globals in there, no anti-globalist police will come. Why? Because it's easy to control them in such a small scope! Like in an instance of a class with a bunch of methods. And when the classes get really large, wouldn't a careful OOP-ist take care to reduce 'instance-global' state as much as possible?
21st Oct 2019, 8:52 PM
HonFu
HonFu - avatar
+ 8
Newt Austin "A member variable in a class is accessible to all member functions in the class. In other words, the variable is "global" to all the functions in the class." Ouch. Don't trust everyone with a PhD :D I think me and HonFu talked about this before, humans can only juggle so many items in their brain at a time, and globals, being accessible anywhere, will always take up one of these valuable slots. Of course globals are necessary, otherwise we couldn't use the standard libraries of half of the programming languages. Some global (or should I say, application-local) variables make sense, for example `document` in javascript. But most variables aren't relevant to the whole application, so why expose them?
21st Oct 2019, 9:04 PM
Schindlabua
Schindlabua - avatar
+ 7
[Part 5 of 5] Emad Now that I've explained how static members aren't a replacement for globals, I should probably provide some details on the purpose of statics. I would say that static members vs class instance members are more about organizing state and functions based on their general vs specific (instance) usages. For example, thing.Id would be tied to a specific instance of Thing. However, Thing.GenerateId() would be a general purpose method regardless of a specific instance and would only need to exist in a single memory address. Static members are therefore tied to the class type itself as a single meta instance while instance members are tied to one or more object instances of the class type. Hopefully this clears things up. Apologies for the lengthy responses. This should conclude my responses. 😉
22nd Oct 2019, 2:58 AM
David Carroll
David Carroll - avatar
+ 7
Tnx alllot. Im so happy with this app. I can ask my questions and Activated Users great professional like you guys can answere me and u actually do it which is amazing😊😊
22nd Oct 2019, 4:05 AM
Emad
+ 7
A C function can use a static variable to retain an updated value through multiple passes of the function but within the scope of the function, so in a few special cases such a static variable can replace a global for the purpose of retaining state but just within the function and the file. This is different to static variables of classes in OOP languages like C# or Java.
22nd Oct 2019, 8:04 AM
Sonic
Sonic - avatar
+ 6
Mirielle🐶 [Inactive] HonFu Hello sis, hello bro, we are here to discuss and learn from each other. Honfu, what you have been said is correct and you too Mirielle. in developement, we all have different methods to do a correct thing, we might respect best practices or not, we can develop a method with 1k line of code and today we can optimise it to be less than 5 line of code. because we are all learners from our faults. What HonFu want to point on, that you can create a global variable that you are going to avoid any suspecious modification on it, but if you work in team, rules change and may be one of your colleagues use the same variable in another methode and your output is not going to be the expected one. that’s why Honfo has mentionned Global variables is something to avoid in some cases if there are other choices. have a nice day all of you brave learners. best regards
21st Oct 2019, 2:12 PM
Bouaoud Mohsine
Bouaoud Mohsine - avatar
+ 6
interesting discussion, i am quite lazy to find where David Carroll shared a topic relating to this, for many functions to have access to a global variable is bad because if an error occurs you will have ro re-test every function to check for which one is broken, i like that post which david share, maybe i should stop being lazy and find it to help others too 😉😉😉 edit: oops found it 😂😂😂 https://www.sololearn.com/post/160420/?ref=app read David's comment on that
21st Oct 2019, 10:08 PM
✳AsterisK✳
✳AsterisK✳ - avatar
+ 6
Emad We are? Your question did not specify C or any language. I would add C as a tag. Now that I know this is C, static will have some additional notes, which I can try to add later. For now, it's time to sleep. 😉
22nd Oct 2019, 7:55 AM
David Carroll
David Carroll - avatar
+ 6
Miika I just saw your answer and you addressed the points I was thinking of regarding static in C. I'm glad you were able to pick up on this being about C. I completely overlooked that based on the context of the discussions.
22nd Oct 2019, 7:59 AM
David Carroll
David Carroll - avatar