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.

  1. The SAME value applies regardless of where it's referenced
  2. The value is referenced in MANY places
  3. The value changes INFREQUENTLY
  4. 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

  1. Data Environment: (e.g., Production vs. Development vs. Testing)
  2. Facility/Branch: name or ID of the location where the program is running
  3. User Preferences: (use SaveSetting/GetSetting to store in HKCU)

Bad examples of global variables

  1. Report Date: this value will likely change frequently
  2. CustomerID: what if you want to run reports for different customers at once?
  3. 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.

Image by Free-Photos from Pixabay