Skip to content

Definitions and assignments

refractalize edited this page Sep 22, 2012 · 1 revision

There is a class of bugs that occur due to inadvertently reassigning variables defined in outer scope. A simple example:

a = 7

do something with a block
    a = "something else"

The problem is this: the inner scope wanted to define a new variable a for its own purposes but instead it reassigned the outer variable. When the inner scope is finished, the outer scope now finds its a is something else. As it happens, this example is so simple as to not really demonstrate the problem. The problem occurs in much more complex pieces of code, involving many more variables and many more levels of scope.

The solution is to be more explicit about definition and assignment, so we'll choose another operator for assignment, := and keep the = operator for definitions. We also forbid shodowing variables, that is, one cannot define a variable that has the same name as one found in outer scope. With these rules, the above example would raise a compile-time error, explaining that the inner a is shadowing the outer a, which is illegal. Instead, the programmer would have to explicitly use the assignment operator :=, if that was his or her intention, or use a different name for the inner variable.

It is also worth noting that field assignments will be affected. Assigning to a field on an object must use the assignment := operator, as in:

object.field := "something"

Whereas, defining a field in a hash literal would involve the definition = operator, e.g.:

{field = "something"}

Now while this eliminates a particular class of bugs present in probably overly complicated code, it introduces some complexities to the programming experience. Programmers are now having to think about definitions and assignments differently, although it is likely this is something that are already doing.

I personally like this feature because it has a nice functional feel to it. Having to type := is a tax on writing imperative code. But I'm not in favour of complicating the programming experience: I don't want people wondering all the time if they're assigning or defining, and not really getting it. I suppose we'll just have to try it out and see.

Clone this wiki locally