views:

1688

answers:

19

Everyone here seems to hate global variables, but I see at least one very reasonable use for them: They are great for holding program parameters that are determined at program initialization and not modified afterwords.

Do you agree that this is an exception to the "globals are evil" rule? Is there any other exception that you can think of, besides in quick and dirty throwaway code where basically anything goes? If not, why are globals so fundamentally evil that you do not believe that there are any exceptons?

+5  A: 

Typically the argument is that you can design the application to get the information in another way. Most people also argue about the fact that it keeps the item in memory, increasing the footprint of the application.

Personally I find that yes, there are times that you need to have globals, HOWEVER, it is VERY easy to over do it, thus the blanket recommendation of avoiding them like the plague.

Mitchel Sellers
+1  A: 

The only exception I can think of is: use globals all you want if you're not sharing your code with anyone.

Even for parameters that supposedly never change, your design will be easier to enhance in the future (not to mention easier to test now) if you don't use globals.

Brian Rasmussen
Even sharing code with yourself can be a problem with googles. :)
EBGreen
+25  A: 

Global variables are used all the time, by many, many programmers. We just call them Singletons now.

DannySmurf
But they are still mostly evil!
Vinko Vrsalovic
Like Vinko said, that doesn't make them better though.
jalf
I think Danny's answer was tongue in cheek. Not sure he is advocating singletons so much as pointing out that people use them instead of globals for better or worse.
EBGreen
+1, but yes, they're still evil for the most part.
Quibblesome
They are just a tool. They can be used for good or evil. :) But people seem to lean toward evil uses.
EBGreen
Not advocating Singletons at all. I try to find a better solution whenever possible, but they occasionally are useful. But they ARE just a cop-out... global variables with a name that lacks the stigma.
DannySmurf
Sadly, I have to upvote this.
Nemanja Trifunovic
No, they are now called Monostate :)
Comptrol
+1  A: 

Once and a great while, there is a need for a shared by all value, but it is seldom. It also depends on the language. I program in VAL3, a procedural language for controlling industrial robots. VAL3 saves the values of global variables along with the code. We use this feature to store values that need to be retained from session to session such as locations for the robot to move to.

Jim C
+1  A: 

I use them for an immutable collection of properties which drive some of the detail of the various packages, where options were needed as a defense against uncertain production requirements. In my case I needed a layer that provided property values to a program running as an applet and as an application.

So no, like most things, I don't think they are evil, just that you need to be careful not to abuse them.

Software Monkey
+2  A: 

Frankly speaking, I do not know any usecase for global variables in a complex project. Actually, I am even against most singletons, because of their abuse as hidden global variables.
Each global variable adds up to the complexity, and the dependencies. Even if "read only", it prevents easy testing and refactoring.

On the other hand, on very simple scripts (throw-away stuff) giving up on quality may be OK, and also using global variables to hold global statuses (like debug flags, etc).

Roberto Liffredo
+2  A: 

They are totally, fundamentally, absolutely, incredibly, astoundingly evil.

In your example exception, how can you guarantee the variables are not modified afterwards? It's only because YOU know they are not being touched and your code is presumably edited only by you and very often (before you forget they are not supposed to be modified).

One noteworthy exception is locks, where every execution thread has to be able to access the data structure to achieve coordination, like Python's GIL. GIL is actually not an example to follow because it's always better to have fine grained locks, but is still an example about where it can make sense.

Vinko Vrsalovic
A: 

The biggest hole in your theory, and one that any good book on beginning programming will point out is what happens when you want to dynamically change those variables? In a multi-threaded environment? Without any clients getting the change in the middle of access? There's a huge difference between a global variable, and a globally accessible variable. You want the latter, because it's easy to control and to modify later.

Jim Barrows
The point is that you *don't* want to dynamically change the variables after program initialization.
dsimcha
+5  A: 

You can avoid global variables, but sometimes you pay for it with code which is harder to read as if you had just used a global variable.

Using global variables depends also on the language. Simply saying: "Don't use them" is too easy. In C++ I'm using global variables only for singletons. But when writing an application in C, using a global variable at the right time (program options, debug flags, application state, ...) increases code readability.

When working on deeply embedded systems written in ANSI C you'll find a lot of global variables (definitions for in- and outputs, application global events, state machines).

Using global variables depends on: - Your kind of application - Application size and complexity - Language features - Readability vs. "I-did-not-use-evil-global-variables" - Application/Library must be thread-safety - Performance questions

Seika
+1  A: 

I really hate globals. I can tell you out of experience, that they are a pain to maintain.

I have seen code, where a global class was defined in one file, created in a second and used in a third.

But the worst I ever saw, was this:

var
  myClass: TMyClass;

procedure TMyClass.IncreaseWTFLevel(ALevel: Integer);
begin
  myClass.FData := ALevel;
end;

It is a class which was created once (but no singleton) and the methods referenced the fields through the instance. Which created interesting bugs when a second instance was needed.

Gamecat
+2  A: 

Yes, that is an exception to the rule. Or rather, the rule shouldn't include cases like that in the first place.

Global mutable state is bad. If your global state is not mutable, then it's not bad. Hell, your class definitions are global, as are your function definitions. No one are complaining about those.

Of course, even in the case of program parameters, you might ask whether it'd be better to make it non-global anyway, so that you can easily pass different parameters to each part of the program, or to make it easier to test various functions, so even then, non-global might be a better option, but in itself, global state is not harmful, as long as it's not mutable.

jalf
And thanks to metaprogramming, class definitions are also mutable...
Christopher Mahan
+1  A: 

Some ad hoc programs are easier or quicker to code with global variables and they don't present a fundamental flaw in the design since the program is unlikely to be changed. And constants, such as pi, also seem OK to me in the global scope. I can think of quite a few other examples that it would be OK for too.

There are no hard and fast rules for good design; it's a guideline that is treated with excessive respect as if code with globals will never be stable or readble - it can be, it just often isn't.

+68  A: 

Here's a cheap way to get rid of all global variables: put all your code in one big fat class and change the global variables to member variables. Nothing has changed as far as the maintainability of your code, but technically it no longer has global variables.

It's better to talk about size of scope than whether or not something is global. "Global" just means maximum scope. Instead of saying "global variables are bad," I think it's more helpful to say "minimize variable scope."

A global variable in a 100-line program has a scope of 100 lines. But a member variable in a 1000-line class has a scope of 1000 lines. The latter may be worse.

John D. Cook
A: 

Globals are as good or as evil as the person who implements them. There is nothing wrong with global variables, goto, or eval... they're usually not the best choice for solving problems simply because they create more problems then solve. Seeding an application with reads/writes on a global variable makes all uses of that global dependant upon it and increasingly difficult to debug or refactor later. Furthermore it becomes next to impossible to setup tests on your code because you've got the unknown factor of what your global variable is at... made worse by abusing singletons.

David
A: 

Frankly, I can't think of a single exception of that rule. Global variables are evil, period. And that includes singletons, public static member variables and other ways to disguise globals.

Nemanja Trifunovic
+4  A: 

In embedded programming, tightly coupled (I prefer 'cramped') as it tends to be, we to use them to store parameters pertinent to the whole device.

Also, on the performance side, on my last project I used some just to avoid the overhead of passing pointers/parameters around.

I avoid them as much as possible, as it is so easy to make a mistake and can be a pain to maintain the code, but sometimes it's all you have.

Marcelo MD
+1  A: 

I think global variables (or singletons/public static/etc) aren't necessarily evil if they don't change behavior based on state. For instance, a random number singleton, like Util.NextRandom() isn't terrible. Yes, it messes up isolation of concerns somewhat, and makes code harder to test, but it in some regards makes the code cleaner since you aren't maintaining a reference to a single one, and passing it throughout your hierarchy just to have that one function available. Similarly the flyweight pattern of some globally available resource has the same reasoning, since the same input always has the same output, just different running times.

FryGuy
A: 

The ONLY case i know of is quick throwaway/debug code that should be deleted when stable. As for program parameters, i'd have them in a program parameter class which you may have more then 1 of (so you can run func a, b in this setting and run b and c with another setting w/o modifying the original class) or have the data passed in to child class that require the data (this seems to be the best way to do this)

I dont care what anyone else says. singletons are as much evil as global vars are and maybe more. If you see a global var you know its a global var, if you see a singleton class you may not recognize right away (depending how its written). Remember, if i only NEED one of it, it does not mean it is or should be a singleton.

acidzombie24
+1  A: 

Global variables are useful for weeding out weak programmers. If your code is complex enough, the weak programmers won't be able to grok it, they fail, and you are left with the best programmers. In this way they can actually increase software quality in the long run.

Alphonse