With AMD style modules in JavaScript is there any benefit to namespaces?
Posted
by
gman
on Programmers
See other posts from Programmers
or by gman
Published on 2014-05-27T05:12:31Z
Indexed on
2014/05/27
9:54 UTC
Read the original article
Hit count: 289
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?
© Programmers or respective owner