I also have the pleasure of teaching R to undergraduate students who have no experience with programming. The problem I found was that most examples of when globals are bad, are rather simplistic and don’t really get the point across.
Instead, I try to illustrate the principle of least astonishment. I use examples where it is tricky to figure out what was going on. Here are some examples:
-
I ask the class to write down what they think the final value of
i
will be:i = 10 for(i in 1:5) i = i + 1 i
Some of the class guess correctly. Then I ask should you ever write code like this?
In some sense
i
is a global variable that is being changed. -
What does the following piece of code return:
x = 5:10 x[x=1]
The problem is what exactly do we mean by
x
-
Does the following function return a global or local variable:
z = 0 f = function() { if(runif(1) < 0.5) z = 1 return(z) }
Answer: both. Again discuss why this is bad.