[Tutor] global variables

Alan Trautman ATrautman@perryjudds.com
Thu Dec 5 11:23:07 2002


why are global variables bad?

They are not always bad. As has been said in other posts all larger programs
will have some, especially if they use GUI's. It is good to have the view
that they are to be avoided to allow the programmer simplify the core items
of their program to as little as possible.

A function should depend on items passed in to function. It should return an
expected value to the calling function. The lack of a global value should
not stop this process but frequently is used to modify it. For example:

Using a simple shape drawing program that takes coordinates, and uses
functions, draws circles and squares. If a circle function is called the
response will vary according the preferences of the user. Say the current
user likes a objects filled in in blue and in the setup of the program this
value is placed in a global variable. The circle function will operate
properly given good values. It will then look to see if the global hold a
user selected value. In this case it will draw the circle with blue but if
nothing had been stored then the default color would be used.

In this example the information could be passed along with the coordinates
but since the person could draw many objects it is kept as a global to
maintain consistency throughout the program.

IMHO that is the key to successful use of global variables. They must be
needed to maintain the consistent functionality to the use throughout the
program. A global that you do not reference frequently in many classes or
functions needs to be examined. I very rarely have more that one item as a
global that is not primitive (int, float, string) when I program to keep a
program stable.

Alan