2

Coming from C++ originally and seeing lots of Java programmers doing the same we brought namespaces to JavaScript. See Google's closure library as an example where they have a main namespace, goog and under that many more namespaces like goog.async, goog.graphics

But now, having learned the AMD style of requiring modules it seems like namespaces are kind of pointless in JavaScript. Not only pointless but even arguably an anti-pattern.

What is AMD? It's a way of defining and including modules that removes all direct dependencies. Effectively you do this

// some/module.js
define([
    'name/of/needed/module',
    'name/of/someother/needed/module',
  ], function(
     RefToNeededModule,
     RefToSomeOtherNeededModule) {

  ...code...

  return object or function
});

This format lets the AMD support code know that this module needs name/of/needed/module.js and name/of/someother/needed/module.js loaded. The AMD code can load all the modules and then, assuming no circular dependencies, call the define function on each module in the correct order, record the object/function returned by the module as it calls them, and then call any other modules' define function with references to those modules.

This seems to remove any need for namespaces. In your own code you can call the reference to any other module anything you want. For example if you had 2 string libraries, even if they define similar functions, as long as they follow the AMD pattern you can easily use both in the same module. No need for namespaces to solve that.

It also means there's no hard coded dependencies. For example in Google's closure any module could directly reference another module with something like var value = goog.math.someMathFunc(otherValue) and if you're unlucky it will magically work where as with AMD style you'd have to explicitly include the math library otherwise the module wouldn't have a reference to it since there are no globals with AMD.

On top of that dependency injection for testing becomes easy. None of the code in the AMD module references things by namespace so there is no hardcoded namespace paths, you can easily mock classes at testing time.

Is there any other point to namespaces or is that something that C++ / Java programmers are bringing to JavaScript that arguably doesn't really belong?

2 Answers 2

2

Executive summary below.

I should actually start a blog instead of writing it here, but hey. live with it ;) this is also a opinion, everything in this 'answer' is how I program, and what I think is best. Don't aggree? feel free to send and email to /dev/null or comment :)

I personally believe that JavaScript and namespaces should not be used together. JavaScript is a JIT language. And that gives us a lot of good stuff to work with.

The biggest speed-pain websites have are extra HTTP requests that get extra resources from the server. Everthing inside the and slows down the loading speed. Webdevelopers then tend to only load critical libraries in the head (modernizr,...) and load al the other JS at the bottom of the tag.

This works in modern browsers since they start rendering once they read the first line of the document. The page however hasn't finished loading untill all JS file shave been loaded. So visualy users will have a better responsetime, but this is simply because we defered the loading.

So we added Asynchronous loading techniques. Instead of add a tag we add a small script that writes a tag to the DOM. The small script that creates the tag is loaded fired synchronous, but the loading of the itself happens asynchronous and does not slow down page-loadtime (i.e. the domready event doesn't wait for this to load). But then there is the problem of dependencies. We have no control over the order that these scripts load now. (A good example of this is the GA asynchronous script).

In comes AMD. Instead of loading all JS files that we might need somewhere in the application (one could add some optimization in the views/CMS but that just feels wrong) we load nothing (just the AMD loader) and defer the loading of everything else for later.

Then, often on a domready event or similar (bottom tag) we start our application. e.g.:

var myFancyStartUpModule = require('my/fancy/boot/module');
myFancyStartUpModule.init();

Now, lets say for some reason, we need a second instance of our fancy boot module. So one would do:

var mySecondFancyStartUpModule = new FancyStartUpModule();

This ofcourse errors. So we try this:

var mySecondFancyStartUpModule = new my\Fancy\boot\Module();

Again, syntax error. Ofcourse, forgot. Namespaces don't actually exist. What does exist is an object my, that has the object fancy,... So lets use it.

var mySecondFancyStartUpModule = new my.fancy.boot.Module();

So we are using object to namespace (ieuk) and this will still error because my.fancy.boot.Module doesnt exist in the window scope. And that is the good stuff about javascript.

Because everything of my fancy module is defined inside that define function it doesn't exist in the window scope. Meaning that everything that wants to use that piece of code, has to use the require() (or set dependencie in define()). This gives you the sweet pieces of javascript like on the fly object creation, binding of this, prototyping but the robustness of a IOC-like style of programming.

I always tend to use a Adapter-pattern like style of programming in my AMD scripts. Instead of writing

require('vendor/fancy/module/for/pdf');

I have a pdf adapter:

require('app/adapter/pdf');

Now, i find this really sweet pdf library not written by fancy met by ultraFancy. I simply change one line of code in my adapter, and suddenly everything in my application uses the new ultraFancy pdf library.

Executive summary:

To answer your question. Namespaces in JS feel really stupid. Because namespaces don't exist in JS. However, we doe have objects with public arguments. And these arguments can be objects as well. And we can add stuff to objects on the fly (really nice). But writing new namespaced.module.inside.an.object(); just doesnt feel right imo. Simply because we not only have molested those nice objects, there is also an unused object in the window object. All code is accessible, and oh boy, I don't trust my self with that much power. A I'll just do a quick fix for now turns into I'll just add this code to the previous fix codebase and quickly becomes require('app/fixes/all.min').

So, don't use namespaces in JS, you don't need them. Think of all those molested objects :(

-1

For the HTTP requests, use a combohandler my friend. :) Very simple either in PHP/NodeJS and makes cache-ing trivial. Most AMD module loading frameworks have one available, it is almost a given.

As an example: https://www.npmjs.com/package/combohandler-patched

It is only through lack of knowledge that AMD apps (or any for that matter) do not have things such as server-side combohandlers (or even client-side ones, if it had to be monkey patched enough).

In addition, most AMD style libraries (e.g. Dojo) allow for namespaces particularly for the benefit of fixing the issues which were mentioned above where you can create a loader configuration that renames these things.

1
  • 1
    How does your answer come close to answering the question "is there any benefit to namespaces?" Jan 31, 2015 at 2:02

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.