So, usingsimas a global seems justified. Nevertheless, if we were bound
and determined to avoid using globals, we could have placedsimas a local
withindosim(). This function would then passsimas an argument to all of the
functions mentioned in the previous paragraph (schedevnt(),getnextevnt(),
and so on), and each of these functions would return the modifiedsim.
Line 94 for example, would change from this:
reactevnt(head)
to this:
sim <- reactevnt(head)
We would then need to add a line like the following to our application-
specific functionmm1reactevnt():
return(sim)
We could do something similar withmm1glbls, placing a variable
called, say,appvarsas a local withindosim(). However, if we did this with
simas well, we would need to place them together in a list so that both
would be returned, as in our earlier example functionf(). We would then
have the lists-within-lists clutter described earlier—well, lists within lists
within lists in this case.
On the other hand, critics of the use of global variables counter that
the simplicity of the code comes at a price. They worry that it may be dif-
ficult during debugging to track down locations at which a global variable
changes value, since such a change could occur anywhere in the program.
This seems to be less of a concern in view of our modern text editors and
integrated development tools (the original article calling for avoiding use of
globals was published in 1970!), which can be used to find all instances of a
variable. However, it should be taken into consideration.
Another concern raised by critics involves situations in which a func-
tion is called in several unrelated parts of the overall program using differ-
ent values. For example, consider using our examplef()function in dif-
ferent parts of our program, each call with its own values ofxandy, rather
than just a single value of each, as assumed earlier. This could be solved by
setting up vectors ofxandyvalues, with one element for each instance of
f()in your program. You would lose some of the simplicity of using globals,
though.
The above issues apply generally, not just to R. However, for R there is
an additional concern for globals at the top level, as the user will typically
have lots of variables there. The danger is that code that uses globals may
accidentally overwrite an unrelated variable with the same name.
This can be avoided easily, of course, by simply choosing long, very
application-specific names for globals in your code. But a compromise is
also available in the form of environments, such as the following for the DES
example above.
R Programming Structures 173