The beauty of namespaces

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, offline and 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 online::sendMessage() and offline::sendMessage(), you keep a namespace variable called mode and call the methods like this:

mode::sendMessage()

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.

3 Responses to “The beauty of namespaces”

  1. Ruben Swieringa Says:

    Hey that’s pretty sweet, I think it’s weird though that you don’t get any errors about duplicate member definitions (which you do get when you declare the same function once public and once private)..

  2. Theo Says:

    I agree. That namespaces are access modifiers, and vice versa results in some wierd logic.

  3. Stephen R Says:

    Beauty is in the eye of the beholder. But I agree with you – this is beautiful.

Leave a Reply