DEV Community

Mervin
Mervin

Posted on

Why are global variables bad?

Global variables are variables that are declared outside to be accessible by everyone in the application.

But if you search it in goole. The second query result is that global variables are bad. Why?

I think everything has its own pros and cons. And global variables' pros and cons depends on how it is being used. It also depends on how big or small your application is.

For smaller applications, global variables are not a problem. It helps your code to easily pass and access data from other classes and methods. You don't need to pass a variable every time you call a method or class.

Sharing data inside the application using global variables will also help you minimize local variable creation and lesser memory usage.

But for larger applications, using global variables are bad. It will make your application hard to maintain and read. Looking for global variables just to know how they were created or manipulated will take you some time. And in OOP, it destroys the idea of encapsulation.

But if you do understand what global variables are, then you just have to make your own decision in your implementation. Just code at your risk :D

Top comments (19)

Collapse
 
bgadrian profile image
Adrian B.G.

For smaller applications, global variables are not a problem. It helps your code to easily pass and access data from other classes and methods. You don't need to pass a variable every time you call a method or class.

Nope ,not ok, they are a problem everywhere, there are always better solutions. For example each module can have a single instance and return it when called, but it should let the ability to make a new instance.

Everything that uses a global var will be harder or impossible to unit test, ABTest, and refactored.

Collapse
 
mervinsv profile image
Mervin

Yeah. It is really hard to unit test if there is a global var. So is there any pros about global variables that you could think?

Collapse
 
bgadrian profile image
Adrian B.G.

No pros, but I hope you are referring to the App global level.

There are some "file/module level" (private or public) variables that are ok to be used,for cache/memoization, example you have to build a dictionary and you do not want to do that for every function call (512 keys of something) or consts/enums (like in C or Go).

Most of the time I saw global vars being used is to take shortcuts, to avoid refactoring and the usage of better design patterns (by lack of knowledge or by laziness).

In JavaScript - some things will end up the the global scope (window on browsers), by mistake (forget to put var/const/let), put there by the browser or libraries, but it allows a Module architecture so there shouldn't be any global var specifically set by the developer of the app.

There are some languages that do not have Namespaces/Module scopes so using global variables is not a choice

A number of non-structured languages, such as (early versions of) BASIC, COBOL and Fortran I (1956) only provide global variables. Fortran II (1958) introduced subroutines with local variables, and the COMMON keyword for accessing global variables. Usage of COMMON in FORTAN continued in FORTAN 77,[2] and influenced later languages such as PL/SQL. Named COMMON groups for globals behave somewhat like structured namespaces.[3] Variables are also global by default in FORTH, Lua, Perl, and most shells.

Thread Thread
 
mervinsv profile image
Mervin

Thank you. I think using global vars are too bad for webdev.

Thread Thread
 
bgadrian profile image
Adrian B.G.

The worst thing about them is their Mutability, everyone can change them at anytime, causing spaghetti side effects and there is no way to tell who did what when and why.

Collapse
 
fnh profile image
Fabian Holzer • Edited

"It helps your code to easily pass and access data from other classes and methods."

If you need to pass data to a function or a class method, those data clearly should be parameters. In case you have an object, the data might be instance variables. But global variable is not appropriate as a means of passing data. They introduces indirect transfer of control, high coupeling and hinders the ability of the design to be decomposed.

"Sharing data inside the application using global variables will also help you minimize local variable creation and lesser memory usage."

In case you have not noticed: There is nothing to save there, especially nothing that could ever outweigh the cost of labour unnecessarily introduced by the troubles that you are signing up for in the long run, which is caused by side effects that are increasingly hard to spot and even harder to fix because everyone who touches a global variable on which other parts of the system started to rely on.

"Just code at your risk"

Well, do at your risk what ever you fancy, but please refrain from doing so at your employer's, your client's or the general public's risk, since that would be grossly unethical and unprofessional.

And while of course, everyone is entitled to make their own mistakes, may I suggest, that it is better to learn from the experience of those who have been in the field before you - and "Global Variables Considered Harmful" is an insight that dates back to the early 1970es.

Collapse
 
mervinsv profile image
Mervin

Thank you so much. This helps me a lot. I think i will not use global variables anymore or as long as I can manage to make it as a parameter for data sharing.

Collapse
 
geektieguy profile image
Oluf Nissen

What's your perspective on this: Windows apps, typically have a global "App" object. Also, sometimes there's a global thing representing something like "the keyboard" or "the screen". Are there really NO circumstances under which global variables might be acceptable? Even in a browser programming context there's usually "the window" as a global, universally accessible thing. I'm wondering if it's a little more gray than "global variables are always bad"?

Collapse
 
mervinsv profile image
Mervin

Yeah. There are still a lot of global variables being use and are still useful. But I think global variables are frequently use to declare constants inside the app. Like App object in Windows applications.

What I mean by global variables here are the one that is being declared/created by the programmer.

Collapse
 
galvao profile image
Er GalvĂŁo Abbott

"I think everything has its own pros and cons. And global variables' pros and cons depends on how it is being used."

Beautifully put: It's my point exactly. No, global variables aren't bad, booleans aren't a code smell and too many blank lines in the source code aren't a code smell either (saw the last two ones on articles around the web).

A case I cite often are infinite loops. They aren't bad, they are required to, let's say, build an interactive shell application, for an example.

Problem is people are becoming more and more marketers and less programmers, so everyone is in love with bold, catchy and polemic titles nowadays.

Need to use global variables? Go ahead, do it. End of story,

Collapse
 
mervinsv profile image
Mervin

Are you still using global variables in your applications? And how did you manage it? Is it not hard to maintain and expand your app?

Collapse
 
galvao profile image
Er GalvĂŁo Abbott

What I've meant with my comment is that global variables exist for a reason. One shouldn't be afraid to use them, when necessary.

It's dangerous to make such affirmations such as "thing X is bad for you" when it comes to programming, since this can even hinder the development process.

Let's try again: "When possible you shouldn't use global variables". That, for me, is a much more sensible way to put it instead of all the FUD we see going around in this industry.

And yes, there are a few source codes where I do use global variables.

Collapse
 
craser profile image
Grumpy and

I think others have done a great job of talking about why global variables are bad, so I won't pile on.

But I do see a few "big picture" aspects of your question that are worth thinking about.

You seem to understand that you can get away with bad practices in small applications, but that they'll cause trouble in big ones. That's great. The next step is to remember always that every big application is a small application that grew, and every small application may one day be the old version of something huge. Healthy small applications grow into healthy big applications. Write your small applications so that they can grow strong and healthy.

Also, it seems you're early in your career. I enjoyed your post about why you love JavaScript. I love it too. :) For now, I urge you to become very fast and very good at doing things the right way. Seek tools that have good refactoring functionality built in, and study OOP Patterns and techniques nso that you'll have a toolbox of solutions handy and won't have to re-invent them each time you're faced with a complex problem.

I love that you're here, asking questions and really listening to the answers. Your enthusiasm and curiosity and openness will take you far!

Collapse
 
mervinsv profile image
Mervin

Thank you so much. I already have a year of experience in real projects and I'm still learning about refactoring and OOP patterns. I know that this topics are not easy to learn and that's why I'm here. Because I want to learn and get inputs from other developers.

Are there any tutorials or resources about refactoring and OOP Patterns that you could recommend?

Collapse
 
craser profile image
Grumpy and

The classic Patterns book is Design Patterns: Elements of Reusable Object-Oriented Software. It's by no means exhaustive, but it's a great start.

And Twitter is a great place to find and follow great devs working on stuff you're interested in. Dig around, find a few people, follow them, see what they talk about and who they retweet, follow those people, repeat. Before long, you'll find amazing stuff in your timeline with links to CodePen, GitHub, etc, where you can see how people are doing things.

Cheers!

Collapse
 
cathodion profile image
Dustin King

A small program with global variables is equivalent to a single object with instance variables. Just less typing, plus some semantic differences that are imposed by the programming language.

It's probably better to encapsulate the variables somehow if the program gets to be more than one file or a hundred lines or so. Or if it's important enough to unit test or use in a multi-threaded way. This is just part of the process of cleaning it up for future use, along with adding comments.

Collapse
 
mudlabs profile image
Sam

Pro? state management, within a browser environment 🤞

Collapse
 
rbanffy profile image
Ricardo Bánffy

s/goole/google/

Collapse
 
mortoray profile image
edA‑qa mort‑ora‑y

I think the question is meaningless as it isn't clear what "global" means.