Pattern: Global Variable


Context

Global variables in Smalltalk exist in a single global namespace, the Smalltalk dictionary. They provide access to an object from any class in the image. In general they are frowned upon because they:

So when should we use a global?

Solution

You probably shouldn't add any global variables (apart from classes, which are global by definition). There are several alternatives: Pool Dictionaries, Class Variables and Class Instance Variables each of which alleviate the namespace problem.

The only sensible use of global variables is for testing purposes when you need to create an object in a workspace and, over time, send it messages by evaluating snippets of code. If you assign this object to a global, this becomes easy, but you must remember to nil its value when you're finished to allow the unwanted instance to be garbage collected.

Known Uses

The View hierarchy uses a Pool Dictionary called Win32Constants which holds all of the Windows™ specific constants. These are available to all instances of View and all instances of all of its subclasses.

The Behavior class defines a class variable called PointersMask which holds a flag mask that can be used to test whether an object holds bytes or pointers.

The ExternalLibrary class defines a class instance variable called default which, for each subclass, is the default instance of that subclass (Singleton)

Related Patterns