Responsible JavaScript: Namespaces

Continuing in my series on Responsible JavaScript, today’s discussion will be on the responsible use of namespaces.

I’ve covered namespaces in JavaScript before, so I won’t go into the mechanics of how to accomplish this. Instead, I’d like to focus on responsible namespace creation and organization.

We’re told quite often that we should namespace everything. I myself am one of the loyal followers of this philosophy, but I also think that it’s important to keep ourselves in check.

Have you ever written anything that looked like this?

fooCom.utils.appManager.myApp.widgets.contactForm.validate();

Ok, so maybe that’s a bit extreme. Maybe not. Over-engineering your namespaces can be just as problematic as not using them at all.

How to responsibly namespace your code

I recommend you always do the following with your namespaces:

  1. Use a namespace wrapper utility to create your namespaces
  2. Segregate application namespaces from library namespaces
  3. Organize libraries component groups
  4. Organize applications into functional groups

The Namespace Utility

Creating namespaces are as simple as creating JavaScript objects.

var myApp = {};

This technique works really well until you start having several apps share a common namespace. If all your apps start off with var myApp = {}; each new app will clobber the previously defined one.

Of course, you can prevent this by checking if the object exists already…

var myApp = myApp || {};

… but who wants to do that at the top of each of their applications? Furthermore, this problem becomes worse when you need to check for nested namespaces.

YUI2 has a wonderful implementation of a namespace utility which will create namespace objects for your application without clobbering existing objects. You can pass it a namespace like myApp.widgets and it will be smart enough to create myApp for you if it doesn’t already exist.

My own version looks like this:

var namespace = function (namespace) {
    var components = namespace.split(/[^a-z0-9]+/ig);
    var context = window;

    for (var i = 0, l = components.length; i < l; i += 1) {
        var component = components[i];

        if (!context[component]) {
            context[component] = {};
        }

        context = context[component];
    }

    return context;
}

Application/Library Segregation

Another common problem is when your application namespace shares the same namespace as your library. This is my biggest problem with the YUI2 architecture because it can quickly lead to massively nested namespaces.

Your application should stand on its own. In the unfortunate, but far too common cases where a library must be replaced, having a standalone application object will save you lots of headaches.

On a similar (and probably less important) thought, it should be noted that developers tend to name libraries after companies rather than giving them names of their own (as you would a project, for example). Companies die, get bought/sold, etc. Do yourself a favor, don’t name your libraries after your company or worse, tie your applications into your companies namespace. You’ll regret it someday.

Library Organization

If there’s one place in code where it’s probably ok to have nested namespaces, it would be library code. Libraries (please note that I didn’t say framework) should be designed so that there is open sharing of components. Wherever there is an overlap of tools, generally a sub-group will need to be created.

I recommend that you avoid the general util bucket unless you really can’t think of anything better.

Application Organization

Applications, on the other hand, are usually fixed modules or running instances of programs in which your utilities live in a common context. Yes, it’s ok to have your util bucket here as there are likely to be lots of utilities your application makes use of throughout it’s execution.

Don’t over-think it

Engineers of all kinds have a common flaw of always trying to improve upon something. Programmers will always try to find a better way to write and organize their code. The key here is to find the balance.

All programs will start off having perfectly organized namespaces, but with time they will deteriorate. Having a system like the above helps to prevent it from falling apart entirely.

This entry was posted in JavaScript. Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>