Skip over navigation

The Importance of Namespace (and a JavaScript solution)

By on Apr 28, 2009 in Tutorials, Web Engineering

Many programs are written to use several smaller programs that all running at the same time. Sometimes this little programs share variables. Sometimes they don’t mean to. This is where the problems start.

When you write some code, it needs to know that no one was messing with its variables while it was out running errands. When your code is all by itself, this isn’t a danger, but when it starts hanging out with other programs, it’s time to watch out.

Namespacing is a programming technique that protects your variables from other programs. Let’s check out an example. I’m going to use JavaScript because I like the Internet, but the concept of namespacing is universal in the world of programming languages.

Your script

var count = 0;
...
<a href="#" onclick="count++;">More, please.</a>
<a href="#" onclick="alert(count);">Where are we?</a>

Some other unrelated and oblivious code

var count = 0;
var numbers = [1, 2, 3, 4, 5];
for (i = 0; i < numbers.length; i++) {
   if (numbers[i] % 2 == 0) count++;
}
alert("There are " + count + " even numbers in there!");

This example does not use any namespacing. Your script sets up a count variable, and let’s you add to it by clicking on a link. When you get bored of that, you can check out how many times you clicked. The second script takes an array of numbers, figures out how many even numbers are in it, then proudly reports its findings when it’s done.

As you can see, the second script assumes it can create a variable named count and does with it whatever it pleases. (And why not? It’s a free country!) The problem is that your script didn’t protect itself. When the second code runs, it will stomp all over the count variable you’ve been furiously clicking to increase. When you get around to clicking on, “Where are we?” you’re going to want to see several significant digits for your effort, not the measly “2” that you are going to get. Your program’s count is not safe from being overwritten by the second program.

While we’re at it, the second program is not safe either. It won’t take long for the second script to run, but if you click on the increment link during that time, the second program will not get the result it was looking for either. I’m guessing, at the rate that you may be hammering on the, “More, please”, it becomes likely.

What are you going to do?

Really, each program needs its own separate count variable, instead of accidentally sharing the same one. This is what namespacing does. Many programming languages have special ways of implementing namespacing. Frequently, it’s as simple as writing your name at the top of your program (naming your space). Not so simple with JavaScript, though. But don’t fret. We aren’t powerless.

Use a different name

The two example scripts bumped heads when they chose the same variable name, count. Makes sense. They are both counting after all. Although, if they had been more specific, there would have been less risk involved.

Your script could have used, numberOfTimesYouWereInclinedToClickTheLink.

And the other program could have gone with, lookyHereWhatIFound.

Less risky, but of course, also ridiculous.

A more realistic solution would be to use a prefix: mkd_count. Those are my initials. This technique would help, but you’d end up having to do that to all your variables. What a pain, and just not pretty.

Scope

Coming to your rescue is another attribute of the JavaScript language (and most other languages), Scope. Within functions, variables retain local scope. This means that variables inside of functions are unknown to code on the outside. Check this out:

var count = 100;
count++;
function makeItCount() {
   var count = 0;
   count++;
   count++;
   alert("Made it count: " + count);
}
makeItCount();
alert("What was that old count anyway?  " + count);

Execute this code, and you’ll find that the two uses of count are actually different variables. One is “the count on the outside of the function”, and the other is “the count on the inside of the function”. The output here ought be:

Made it count: 2

What was that old count anyway: 101

That is cool. It means that you can wrap all your code up in a function. Of course, then you run into the same problem again. What are you going to name your function? When I write code, I like to use function names like hide and addClass and getDownWithIt. How do I protect my getDownWithIt from all the other getDownWithIts out there?

Using Objects

In JavaScript, you can wrap anything up in an object. Check this out:

var MattDeClaire = {
   count: 0,
   add: function() {
      this.count++;
      alert("I'll have " + this.count + " scoops of ice cream.");
   }
};
MattDeClaire.add();

This code is a little more advanced. Let me do some explaining. MattDeClaire is one big variable, called an object. Inside it (wrapped in curly braces) is a variable count and a function add. To access a variable or function inside another variable, you use a dot (.). That is how I called the function add at the bottom of the script. Inside the add function I used a this. The this is a reference to the functions parent variable, which is MattDeClaire. this.count is the same as MattDeClaire.count.

Check out this article for some more object explanation. Here is an article delving deeper into the this operator.

This method allows me to only have to come up with one unique name, MattDeClaire. I used my name because it’s fairly unique, but you could use your name combined with your company name, or the project name, to get more specific.

But, after all that, the code is still not pretty. My name may be pretty, but it doesn’t need to be littered all over the code like that. There has to be a better way.

The Better Way

JavaScript in particular has a very clean, but technical solution. You can create a function, without a name, and then run it right there on the spot. “Let’s see it,” you say?

(function() {
   alert("Boo-yah!");
})();

There sure are a lot of parentheses in there. Let’s break it down.

Simple action: alert("Boo-yah!");

Wrap in a function: function() { alert("Boo-yah!"); }

Wrap in parentheses: ( function() { alert("Boo-yah!"); } )

Execute the whole thing: (function() { alert("Boo-yah!"); })();

This new method creates a magic little garden of protection, where you can do anything you want without fear of variable collision. Let’s see the first example using this new strategy

Your script

<a href="#" id="morePlease">More, please.</a>
<a href="#" id="whereAreWe">Where are we?</a>
...
(function() {
   var count = 0;
   document.getElementById('morePlease').onclick = function() {
      count++;
   }
   document.getElementById('whereAreWe').onclick = function() {
      alert(count);
   }
})();

Some other not so oblivious code

(function() {
   var count = 0;
   var numbers = [1, 2, 3, 4, 5];
   for (i = 0; i < numbers.length; i++) {
      if (numbers[i] % 2 == 0) count++;
   }
   alert("There are " + count + " even numbers in there!");
})();

Now both pieces of code are safe from each other, and can go about using whatever variables they want.
One caveat: Be sure to use the var declaration statement. This is what actually creates the special copy of the variable for you. If you use count without the var declaration, you are using the same count available to scripts outside your garden. Look back at the oblivious code above, and you’ll find they are potentially stomping on someone’s i variable. JavaScript will let you by without using the var statement, so it will be very important to remember to use it.

The Big Picture

Really, namespacing is not primarily a defensive strategy. Yes, it is nice to protect your code from others, but really, you should think of this as protecting others against your code. If you plan on writing some really handy code and then giving it away to people, you don’t want it to stomp all over the place.

In particular, Namespace has been recently becoming more important in the land of JavaScript. Previously, code used was only written by the page author, without intermingling in foreign code. Now with the rise of JavaScript frameworks such as Prototype, MooTools, jQuery, and many others, the bulk of the code on a page is from somewhere else. You might hear about unobtrusive JavaScript. Namespacing plays a key part in writing code that does not intrude on the code of others.

So go out there and right some code that plays nice.

Other Resources

Namespace Explanation
Namespaces in JavaScript
Play Nice With Others
JavaScript Namespaces

Hey! This wasn't written by a pride of lions! It was written by , who does awesome work at Loud Dog, a digital branding firm in San Francisco that helps businesses express themselves authentically via identities, websites, and marketing collateral.

If you want us to do awesome work for you, if you have a question, or if you're just feeling lonely and want to chat, we want to hear from you!

Get in touch

Comments

  1. Dan says:

    Great article, I cant help but notice the last line says “right” some code… is this a typo or some sort of pun?

    • Josh Orum says:

      Thanks for noticing! It’s been so long since this article was written, I actually don’t remember if it was intended or not.

Leave a Reply

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