Saturday, December 1, 2018

C5.1 Namespaces

When you are writing small programs you may never run into the namespace problem. Once you start using libraries, especially if you use multiple libraries, the namespace problem comes into play. Let us say you had a library that had a function for displaying hello. This library is called namespaceIssue.js and may look something like this:

message = "Hello!"
function sayHello() {
return message
}

Now lets say you wrote the following page that uses the library:

<!DOCTYPE html>

Namespace issue demo


Namespace issue demo









You would expect this program to display the words hello and goodbye. This is not what happens. Instead, it displays goodbye twice. Why? The library used the variable message to store the message that the sayHello function would display. The script in the html file uses message to store the goodbye message to display. It overwrites the variable which the library was using. For a small program like this it is a trivial problem to solve, but when the size of your program increases, especially if you are using code provided by third parties, this problem of variable (and function name) collision becomes a huge problem.

The solution to this problem is namespaces. The idea here is that you have a unique namespace for your program and all the variables for that program go into that namespace. Since each namespace is separate, you can have the same variable name in each of the namespaces without any conflict. In JavaScript, namespaces are created by creating a object with the name of the namespace. Here is the demo above re-written to use namespaces.

namespceUsed = {}
namespceUsed.message = "Hello World!"

function sayHello() {
return namespceUsed.message
}

It is possible to nest namespaces by having another namespace object as part of a namespace object. This is very commonly done to have library namespaces stored under a single unique namespace that you have control of. The convention is to use your domain as the unique name with appropriate names for the libraries under that domain. Some companies will take this a step further by having the root domain as the first namespace object, followed by their domain, followed by their library. This leads to the problem of declaring a namespace without overwriting other namespaces. The solution is to use the following way of declaring a namespace:

com = com || {}com.spelchan = com.spelchan || {}

It is a good habit to use namespaces for any script that you are loading. I generally don’t bother with the com root namespace but if Spelchan was a more common word, then it may be a good idea. 


No comments: