Global Variables Versus Local Variables

◀ The More Source Files, the Better?▶ Class
Amazon The main difference between a global variable and a local variable is that a global variable can be accessed anywhere in the program while a local variable is visible only inside the module it resides.

In general you should avoid using global variables for the following reasons:
  • Global variables make a program hard to maintain because any source file of your program could potentially manage the global variables in some ways. Suppose you are to examine how a global variable is used you'd have to examine every single line of every single file of your program application!
  • Global variables are dangerous because it can be changed anywhere! When you find a bug in your code which has to do with some global variable imagine how difficult and time consuming it is to examine every usage of the global variable!
Local variables are a lot safer because other functions cannot affect them. Once you are done with them inside the module they no longer exist and cannot be the cause of a bug to the rest of the program.

Therefore you should stick with local variables. You can, however, use global constants as they are not changeable throughout the life cycle of a program.
However if the business logic requires that some data be constantly accessed and updated across multiple places then you’ll need to use global variables. Such requirements should not be common.

A snail can sleep up to 3 years without ever waking up.
◀ The More Source Files, the Better?▶ Class

Questions? Let me know!