Another possible solution to the global scope debacle

I have taught absolute beginners (other languages) and is indeed not really that difficult to introduce scope to them in a way they understand IF you can do it at the appropriate time (i.e. when introducing functions), and if it is a the version of scope as implemented in any other language:
You generally start with operators, variables and loops. Assigning something to a variable and then doing something with it in a loop is an extremely common pattern (I am convinced, even without checking, that the v1 change invalidated code in the majority of pre v1 tutorials). Having to explain that they have to use global to access the variable right in front of loop (for no apparent reason) is going to be difficult. The easy place to explain scope is functions: you have a separate piece of code that you are calling from another location, so there it is logical that the variables are contained to that part. You are also giving the values from your current location/scope needed by the function as parameters. One of the worst things of v1 scope then is that at this point you are going to have to explain that what they learned in the beginning (putting globals to get at the variable in front of the loop) does not apply if you put it in a function.

Some of the other suggestions here are even more complex and difficult to explain than v1. In my experience, if I start needing a lot of exceptions and lengthy explanations, I am usually on the wrong track (KISS principle). The original proposal by @jeff.bezanson is simple and consistent, and poses a very limited amount of incompatiblity.

8 Likes