In a recent article, I wrote about the dangers of over-reliance on global state. But global variables do have their place. Here are the four criteria I recommend for deciding whether to use a global variable.
- The SAME value applies regardless of where it's referenced
- The value is referenced in MANY places
- The value changes INFREQUENTLY
- The answers to 1-3 won't change in the FUTURE
If you can answer yes to all four of the above questions, you have a good candidate for a global variable. That still doesn't mean it should be a global variable. Your first instinct should ALWAYS be to avoid global variables, because you can never definitively answer Yes to number four above.
One of the most difficult refactorings in programming is to root out and replace all references to global state. The best way to avoid such a fate is to forego global variables right from the start. In that spirit, here are a few examples of good and bad global variables.
Good examples of global variables
- Data Environment: (e.g., Production vs. Development vs. Testing)
- Facility/Branch: name or ID of the location where the program is running
- User Preferences: (use SaveSetting/GetSetting to store in HKCU)
Bad examples of global variables
- Report Date: this value will likely change frequently
- CustomerID: what if you want to run reports for different customers at once?
- Whole-house Water Temperature
Rule of Thumb
If you can set a variable's value once at startup, it's a good candidate for a global variable.