When are global variables actually considered good/recommended practice?

Global variables imply global state. This makes it impossible to store overlapping state that is local to a given part or function in your program.

For example, let stay we store the credentials of a given user in global variables which are used throughout our program. It will now be a lot more difficult to upgrade our program to allow multiple users at the same time. Had we just passed a user's state as a parameter, to our functions, we would have had a lot less problems upgrading to multiple users.


Global variables aren't generally bad because of their performance, they're bad because in significantly sized programs, they make it hard to encapsulate everything - there's information "leakage" which can often make it very difficult to figure out what's going on.

Basically the scope of your variables should be only what's required for your code to both work and be relatively easy to understand, and no more. Having global variables in a program which prints out the twelve-times tables is manageable, having them in a multi-million line accounting program is not so good.


I think this is another subject similar to goto - it's a "religious thing".

There is a lot of ways to "work around" globals, but if you are still accessing the same bit of memory in various places in the code you may have a problem.

Global variables are useful for some things, but should definitely be used "with care" (more so than goto, because the scope of misuse is greater).

There are two things that make global variables a problem: 1. It's hard to understand what is being done to the variable. 2. In a multithreaded environment, if a global is written from one thread and read by any other thread, you need synchronisation of some sort.

But there are times when globals are very useful. Having a config variable that holds all your configuration values that came from the config file of the application, for example. The alternative is to store it in some object that gets passed from one function to another, and it's just extra work that doesn't give any benefit. In particular if the config variables are read-only.

As a whole, however, I would suggest avoiding globals.