Contextual programming

When working on a large project, it is usually advisable to break your code up into smaller portions. In many languages, these are called shared libraries: smaller chunks of code that can be reused as needed throughout this and other programs.

In many languages, such as PHP, evaluating the contents of another file necessarily means that its code is run in the current namespace. This means that if you were to run the following code in PHP:

$foo = "bar";
require_once("some_file.php");

# Contents of some_file.php:
$foo = "baz";


Can you guess what $foo now evaluates to? $foo has been overwritten. To get around this, we can abuse a class to create a singleton-like object:

$foo = "bar";
class Something {
public $foo = "baz";
}
$context = new Something();


We now have two contexts, main, where $foo = "bar," and $context, where $context->foo = "baz."

In Python, we avoid this altogether:
foo = "bar"
import some_module

# Contents of some_module.py
foo = "baz"


In the Python example, foo is still "bar." However, we now have a new symbol, some_module.foo, which evaluates to "baz."

newLisp has a similar concept, but slightly lower level, and somewhat more limited (in that all namespaces are children of the MAIN namespace, and cannot be nested, as in Python). It also gives you greater control.

(set 'foo "bar")
(context 'SOME-CONTEXT)
(set 'foo "baz")
(context 'MAIN)


In newLisp, 'foo still evaluates to "bar", and 'SOME-CONTEXT:foo evaluates to "baz." Really, of the three, only PHP comes out the poorer here.

If I were comparing the languages, I would say that Python really wins out with contexts. Having nested modules eliminates the need to misuse classes and likewise prevents symbols overwriting each other.

newLisp's implementation is extremely useful as well, but somewhat hindered by its lack of nesting.

PHP is the one that really takes a hit here. It's complete lack of programmer-controlled namespaces forces misuse of other parts of the language and encourages bad coding - for which I am just as guilty as anyone.