[Tutor] global variables
Bob Gailer
ramrom@earthling.net
Thu Dec 5 10:55:01 2002
>At 23:16 2002-12-04 -0600, david wrote:
>why are global variables bad?
Any program that is not trivial will have at least one global object, which
will usually be a function definition, or a class definition with at least
one global instance.
Within that object/definition there will likely be variables and/or
attributes whose lifetimes are that of the function execution or of the
instance, and whose values are needed for various durations depending on
the nature of the program. If the program is a long-running event driven
process, it will need to remember certain things for a long time. How and
where one stores these things is a matter of personal choice; the effect is
the same as having "global variables".
The arguments in the other responses to this thread are for modularization;
keeping related things close rather than far (remember Yourdon &
Constantine? Tight cohesion, loose coupling). I have found that breaking
large systems into modules is really helpful; each module may have one or
more variables/objects that retain values as long as needed.
My first Python project (in which I learned a lot) has over 20 modules,
which are imported at various times. This lets me have lots of edit windows
open (using Pythonwin), making it easy to find and edit code. Some modules
are "run' once; some retain certain things (e.g. a log file) for a long time.
My conclusion is that nothing is bad or good per se. It's a matter of
taste, style, and how easy it is to read and maintain the code.
Modularization is (IMHO) the key.
Bob Gailer
mailto:ramrom@earthling.net
303 442 2625