Click here to Skip to main content
15,891,184 members
Articles / All Topics

Robert’s Rules of Coders: #2 Avoid Global Variables

Rate me:
Please Sign up or sign in to vote.
4.87/5 (6 votes)
2 Aug 2015CPOL2 min read 11.2K   4   8
Global variables are variables that can be accessed from anywhere in the program.

Global variables are variables that can be accessed from anywhere in the program.  It is appropriate to use a global variable when you have a value that is a constant and thus won’t change as the program runs, but it is rarely appropriate to use global variables for values that change while the program is running.

Functions should usually return the same output when given the same inputs.  Global variables in functions can cause the function to return different values, making the function less reliable and more difficult to write unit tests for.

A Bad Program With Global Variables

A Bad Program With Global Variables

In the block of code above, you can see that the value returned from CalculatePrice() is not predictable.  In the first case it returned 11.00, but in the second case it returned 10.50 for the same inputs.  Here is a second version of the program:

Same Program Without Global Variables

Same Program Without Global Variables

The second version of the program has the following advantages:

  • The programmer can see all the factors that affect the TotalPrice.  None are hidden.
  • The programmer can write unit tests against the CalculatePrice() function more easily.
    • Assert.That( CalculatePrice(4, $2.5, 10%) = 11.00)

The problems with using global variables include the following:

  • Global variables can be modified from anywhere in the program, making the output of functions using them less predictable
  • Rules that you code in one place about setting the value of a global variable may not be adhered to in other places. For example one block of code may do this:
Setting Global From Spot 1

Setting Global From Spot 1

But another block of code in the program may do this:

CodeArt2-4

Setting Global from Spot 2

  • A function or component that uses global variables becomes “tightly coupled” to the other components that use the global variable.  This entanglement increases programmatic complexity which means the program is probably more difficult to maintain and enhance, and also that it is difficult to replace one component of the program without affecting others.
  • In multithreaded programs, global variables may not be thread-safe.
  • In some languages, global variables make it difficult to add new components to an existing program because the new component may contain its own global variables with the same name.

When you have an object that you think should be global so that it can be used everywhere, you should probably use Dependency Injection.  Don’t be deceived by the Singleton pattern for a global variable replacement because that often becomes just a more complicated version of a global variable.


License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior) Kraft Software LLC
United States United States
Rob Kraft is an independent software developer for Kraft Software LLC. He has been a software developer since the mid 80s and has a Master's Degree in Project Management. Rob lives near Kansas City, Missouri.

Comments and Discussions

 
GeneralMy vote of 3 Pin
Frank T. Clark4-Aug-15 8:39
professionalFrank T. Clark4-Aug-15 8:39 
GeneralRe: My vote of 3 Pin
Rob Kraft4-Aug-15 9:54
professionalRob Kraft4-Aug-15 9:54 
GeneralRe: My vote of 3 Pin
Frank T. Clark4-Aug-15 11:20
professionalFrank T. Clark4-Aug-15 11:20 
(Why are the paragraphs being run together? Why is Markdown not working?)
\\

Perhaps I am being too precise but the phrase "it is rarely appropriate to use global variables for values that change while the program is running" seems far too restrictive for the real world. If you are interested in a suggestion for alternate expanded wording, I could suggest...
\\

It is highly recommended, wherever possible, to use a global variable when you have a value that is a constant set at compile time and can not change as the program runs. For example, it is very important to avoid the use of "magic numbers" in your functions, which should be given a descriptive name as a global constant/variable.
\\

There are many cases where a global variable is given a value during program initialization but does not change as the program runs. There may be a few cases where a global variable is given a value during program initialization that rarely changes as the program runs. Nevertheless, it is rarely appropriate to use global variables for values that change a lot while the program is running. In most cases, it is better to pass changing values as function arguments. It is also appropriate to limit the scope of global variables to class objects you define to encapsulate a state within a program.
\\

So many details! (heavy sigh) So much confusion...
GeneralRe: My vote of 3 Pin
johnnysaucepn21-Aug-15 2:56
johnnysaucepn21-Aug-15 2:56 
Questiononly when considering the value as fixed Pin
ADemontis4-Aug-15 1:36
professionalADemontis4-Aug-15 1:36 
Question’ Pin
Jeremy Falcon3-Aug-15 11:43
professionalJeremy Falcon3-Aug-15 11:43 
SuggestionGlobal Variables: A Coder's Best Friend Pin
MacSpudster3-Aug-15 8:49
professionalMacSpudster3-Aug-15 8:49 
GeneralRe: Global Variables: A Coder's Best Friend Pin
Rob Kraft3-Aug-15 10:00
professionalRob Kraft3-Aug-15 10:00 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.