It is my opinion that globals are necessary __sometimes__.
You just can’t get around the fact that you need them, at times.
You can think of a member variable as actually .. a global variable.. within that class!
The best reasons NOT to use globals are
The problem with global variables is that since every function has access to these, it becomes increasingly hard to figure out which functions actually read and write these variables.
So to understand how the application works, you pretty much have to take into account every function which modifies the global state. That can be done, but as the application grows it will get harder to the point of being virtually impossible (or at least a complete waste of time).
– Brian Rasmussen
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.
- Are global variables bad?
- Global variables: When ARE they acceptable?
- ok , global variable is condemned, singleton is despised, what’s the alternative?
- When is it ok to use a global variable in C?
- ibm.com: Use your singletons wisely
- code.google.com: Why Singletons Are Controversial