layout: post
title: Identifier Scope
-

{{ page.title }}

7 November 2011

Identifier scope

A variable can have the following scope

Possible ways of expressing scope information

  1. identifier names are not qualified by prefix, identifier assumes lexical scope
  2. Qualified identifier names

There are several problems with this approach:
Problem: One also has declare a variable somehow before using it, as one needs to know if this is a local or a global or whatever scope.

Problem: one has to assume a default; a variable without special declaration is often assumed to be global; one has to declare a variable within function scope in order to say that this is a local variable. I would argue that this is not very intuitive choice, made by such languages as Javascript, Perl, Python, Lua etc. I would argue that the most frequent use of a variable inside a function is that of a local variable.

Problem: it is not clear what a variable reference means by looking at its use;

Qualified identifiers

Qualified identifiers_:http://en.wikipedia.org/wiki/Scope_(computer_science)#Qualifiedidentifiers
most often some prefix is added before the identifier name – prefix says if this identifier is local, instance variable, or class instance or global.

For example in Ruby one has the $ prefix to tell that a variable is used as a global and @ prefix to tell that a variable is used as a object member. Or in Javascript one says this.variablename that tells if one means to access a class member.

I think that Qualified identifiers are better for code readability, one knows the context of a variable usage by looking at it; also it avoids the need to declare variables before assignment.

Qualified identifiers may be a very verbose way of expressing variable usage, but well, I it makes you more aware of what you are doing, which can be of benefit;

Pooh language

So for the Pooh language we will have
_this . _ variablename – a field in an object instance
_global . _ variablename – a global
_outer . _ variablename – reference to captured variable of a closure

No specifier: if a variable is used within a function and has no specifies, then by default it is assumed to be a local variable or function parameter;

If a variable is used in global scope without any specifiers, then it is assumed to be a global variable.