Take the 2-minute tour ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free, no registration required.

Ok, so this is a bit of a devils advocate question really.

When are global variables ok, and if never, what would you use as an alternative?

An interesting side-case to this question, how is a public static class field different from a global?

share|improve this question
3  
Code Complete, 2nd edition, §13.3. –  Jerry Coffin Feb 15 '11 at 0:55
    
Multithreaded applications pretty much require global variables. –  aqua Feb 15 '11 at 4:34
    
See Software Coupling –  PP. Feb 15 '11 at 8:26
2  
@aqua Multithreaded applications are where global variables can be most damaging. Everyone hates complex locking logic. –  luiscubal Aug 18 '13 at 19:31
    
@aqua: Thread-local storage is the new anti-pattern. Frameworks that use thread-local objects present technological fractures between frameworks. For example, WinForms, WPF, ASP.NET and TPL each create their thread-local objects; for this reason, they (at best) leak kernel objects, or (at worst) do not interoperate. How nice for a technological giant trying to unify its R&D efforts. connect.microsoft.com/VisualStudio/feedback/details/648683 –  rwong Aug 18 '13 at 21:16

9 Answers 9

So far as I know, a public static field is basically a global given that it can be called from anywhere with the exception that it does not clog the namespace.

The only time I personally use 'global' variables in my code are in the form of public static fields that are immutable. In this case there is no need to worry about the value being screwed around by other parts of the program and of course its a lot nicer than having a dozen variables with the same permanent values in each class.

share|improve this answer

Personally, I use globals for runtime configuration - if a configuration property is loaded at application startup, and only changes infrequently (and only then from one place), it's terrible and error-prone to pass it around to every method that might need to use it at some point. Better off using something that can be brought into scope from anywhere that needs to use it, as that doesn't clutter up and obscure your method signatures and call sites.

share|improve this answer
    
Would you use a pure global for this or a public static/Singleton? –  Slomojo Feb 15 '11 at 0:59
1  
@Slomojo: Definitely not a singleton. Depending on the situation, either statics on a configuration class, or plain globals with a CONFIG_ or CFG_ prefix. –  Anon. Feb 15 '11 at 1:01
    
+1 the one change I would suggest is to say "...error-prone to pass it around to every other method in every other class". Otherwise It can be scoped to class with whatever serves that - singleton I think. –  Michael Durrant Feb 24 '12 at 3:58

Excluding real time/embedded systems, you should only use globals for constant values, really. If you feel that you can't solve your problem without them, you are probably doing something wrong.

Also, look into Singleton pattern, it cold provide a better solution for globals in those situations when you need something to have global access point.

share|improve this answer
8  
I'd probably suggest avoiding Singletons. –  Slomojo Feb 15 '11 at 1:10
    
I'm not suggesting that singletons are great, but I still think they beat global variables by a lot. –  Davor Ždralo Feb 15 '11 at 9:39
    
Constant values only need to be accessible in the area / module they're relevant. A constant TIMES_TO_ITERATE_THROUGH_THIS_PARTICULAR_LOOP is only relevant in the one file / class / section where 'this particular loop' appears. –  Cthulhu Feb 15 '11 at 21:17
    
The fields of a singleton are global variables, so I don't see how there's any difference. –  sleske Aug 18 '13 at 19:12
    
@Cthulhu let me quote myself: "in those situations when you need something to have global access point". –  Davor Ždralo Aug 21 '13 at 13:12

It's all about namespaces.

Imagine for a moment that everyone in the world had the same last name. What a mess.

(In India, the Sikhs have all the same last name: Singh --Take a look)

share|improve this answer
6  
It used to be all about namespaces, but now it's about thread safety. –  dan04 Feb 15 '11 at 1:54
4  
@dan04 It's about not having a hideous design with spooky action at a distance. –  Tom Hawtin - tackline Feb 15 '11 at 5:56
    
@Tom: Maybe we can call that, tongue-in-cheek, "Quantum Programming" –  Christopher Mahan Feb 15 '11 at 20:50

The problem with global variables is that you need to be aware of them everywhere in your code. However once you've decided that you need to know about a particular global, there is little further lost in using it heavily. Therefore my opinion is that you should have very few global variables, but the few that you have, you should get maximum mileage out of.

For another example of something I feel this way about, look at the use of mixins in Ruby.

share|improve this answer
    
What example use case(s) would you suggest for these uses of globals? –  Slomojo Feb 15 '11 at 0:58
1  
@Slomojo: An example of globals I don't mind is the use of @ARGV and $_ in Perl. An example I do mind is the use of globals for cheap parameter passing to subroutines. –  btilly Feb 15 '11 at 1:42

Development of critical embedded systems usually involves use of global variables.

Stack sizes are tiny, everything is statically allocated (malloc() is forbidden), global variables are hidden from outside the library they belong to.

share|improve this answer

The two gotchas with globals and singletons are testability and deployability.

For testing, I've seen too many overly-complex testing harnesses just to deal with poorly planned global and singleton lifetimes. Make sure that any such object has clear and simple start up and tear down rules.

As for deployability, there are two cases to consider. Firstly, how will your global object live? Is it in a static or dynamic library? If that global object gets reused for a plugin, will you get extra copies? Secondly, what happens when that global object is dropped in to a parallel application? Is it thread-safe?

On the whole, I figure those reasons mean that globals and singletons are used only exceptionally.

share|improve this answer

Short version: when it makes it easier to reason about the program. Typically cases are some type of global state or static resource that is widely used.

Long version: Tom Hawtin said "with spooky action at a distance"...that is exactly the problem with globals -- you have to know where it is being used and how, or you can get some really weird and hard to track down bugs. Locals are nothing more or less than a strategy to reduce the scope of what the programmer needs to understand in order to reason about the program.

Another side of the problem with knowing where they are used is that you can end up with duplicate globals -- in which case things can get really weird as most of the programs gets and sets var1 while in a couple of places var2 is used to hold the same information. Particularly when multiple people are working on the same code. IDE's can be helpful with finding usage reducing the cost of globals, but they do nothing for duplicates.

The more globals you have the harder it is to keep track of what is happening with them. They should be few and far between.

share|improve this answer
    
Ultimately having mutable globals is a pretty bad idea. The only decent exception is when working in extremely tight hardware footprints, such as with embedded programming. At the very least, candidates for globals in regular programming should be parcelled off into static members of classes or modules, anything that's mutable should also be considered a special case, doubly so when working in a multi-threaded environment. Using locking / futures / promises or some other method of thread/transaction safety. - Since no one else mentioned it see the dining philosophers problem. –  Slomojo Aug 19 '13 at 0:41
    
No doubt threads can make mutable globals harder to work with, but you can get the same basic problem due to events. I agree with the suggestion to put hem in as static members, and would go further and say that ideally they should be PRIVATE static members. –  jmoreno Aug 19 '13 at 15:39

In a horrible VB6 code base that abuses globals like there's no tomorrow, I'm guilty of introducing a new one:

Global CsExt As New TheAppBeingRewrittenInCSharpWhileVb6CodeIsStillBeingMaintained

I think it's one of the few valid use cases for a global object.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.