Namespaces in ActionScript is a concept which I’m not aware of existing in any other language*. I’ve tried to find an example of why they are needed and how they can solve problems that cannot be solved without them, or at least less elegantly without them. Reading Colin Moock‘s Essential ActionScript 3.0 I came accross an example that showed just that. In two paragraphs Moock has convinced me of the beauty of namespaces.
If we organize groups of methods and variables with namespaces, we can use dynamic namespace selection to switch between operational modes in the program. For example, suppose we’re writing an instant messaging application with two modes represented by corresponding namespaces,
online. The application defines two versions of a method named
sendMessage()— one to use in online mode and one to use in offline mode.
From Colin Moock’s Essential ActionScript 3.0, p. 316
What you do is that instead of referencing the methods as
offline::sendMessage(), you keep a namespace variable called
mode and call the methods like this:
When you are online you set
mode to reference the
online namespace, and vice versa. This means that client code doesn’t have to deal with what mode we’re in, only what it wants to do. In this way it’s very similar to the design pattern State, but done in a completely different way.
I find it absolutely beautiful.
* Remember, namespaces in ActionScript are not the same as namespaces in, for example, C++, even if they share the same name.