2012.09.12

Namespaces are Old School

Let’s start with an overly simplified/generalized and mostly wrong history of the JS community during the past decade.

Let’s go back in time 12 years, to the distant year of 2000. JavaScript is being mostly used for form field validation, analog clocks and mouse trails. Nobody really cared about namespace cluttering, all the code resided on the global scope. This is considered the dark age of JS.

Now let’s fast forward 5 years, to the the first stage of the JavaScript Renaissance (2005-2007); libraries like jQuery, Mootools and Prototype.js are getting extremely popular, AJAX is the buzzword of the moment. Augmenting native prototypes was a very common practice and no caution was taken into consideration, the rule of thumb was easy development and brevity. Larger projects started being developed by more people and best practices started to appear. Sometime around this period closures became a popular way of hiding information and IIFE became the De facto standard. Namespaces also became really popular.

Now back to 2012. Everybody knows that augmenting built-in native objects is a bad thing, specially host objects. Polluting the global namespace is also considered a bad practice and many people avoid it as much as possible. It is not uncommon to see people adding their own application code into objects that they don’t own, proving that they don’t really understand why they shouldn’t have globals to begin with, but at least we are moving towards the right direction. <rant>Polluting any namespace is a BAD thing, not only the global scope, you should NOT put your application code into the $ object…</rant> Script loaders and package managers are becoming more popular each day, node.js is the buzzword of the moment and Harmony might become a reality and provide a native module format.

OK, no more history… Let’s see some code.

Why Namespaces?

Namespaces were created as a way to avoid name collisions and to group code by context. Some variable/function names are very common and it is very easy to get into conflicts. Keeping all your code inside a sandbox reduces this chance, it also improves the code organization.

Namespaces in JavaScript

The language doesn’t provide any special keyword to define a namespace so it’s a common practice to use plain objects as a way to emulate it.

var myNamespace = {};
myNamespace.bar = 'this is dog fort';
myNamespace.doFoo = function(){
    console.log(myNamespace.bar);
};

That is a valid way to group methods by context and to avoid name collisions. And it’s been working for the past 10+ years for the JS community, except when it doesn’t.

Verbosity

After you get neurotic about name collisions and/or the libraries/frameworks grow to a certain size it is inevitable that you have nested namespaces like lorem.ipsum.dolor.doSomething() which isn’t fun, specially if it is a method that you use very often.

Namespace cluttering

To avoid the verbosity many libraries started to put all methods inside a single object, jQuery and Underscore.js are famous examples of this poor practice. The chance of name collisions increases a lot, and naming methods becomes harder. Just imagine 2 jQuery plugins that implements the same method with different behavior (plugins are evil BTW), chaos will ensue.

An object with too many methods probably has very low cohesion and that is an anti-pattern. The code gets harder to browse and inspect since everything is mangled into the same object, the namespace should give context to its properties. A method add() inside a userList object probably means “add a new user to the list”, while a method with the same name inside a FOO object can mean hundreds of different things.

Code sharing

A common practice that I’ve seen is to create a global object named as the company/project name. So if the project is for a client named “Foo” the whole application code would be placed into the FOO object. Now if you want to reuse the same code into multiple projects you will need to replace every reference to the FOO object or keep all the shared code into a separate namespace. This doesn’t scale really well and is error prone…

noConflict()

Everything goes well with the namespaces until 2 libs decide to use the same name, or you need to load 2 versions of the same library into the same page. The solution, create a noConflict() method. Now every library that don’t want to create conflicts with 3rd-party code needs a noConflict() method. That is not ideal and extremely error prone, specially when code is loaded asynchronously or you have a large code base with a complex dependency tree.

var _oldNamespace = window.myNamespace;
// reset global reference to previous state
myNamespace.noConflict = function(){
    window.myNamespace = _oldNamespace;
    return myNamespace;
};

It’s 2012, use a module system!

What is the best way (using current JS) to really solve the global name conflicts? Don’t use globals at all!

With a module system like AMD or CJS you don’t rely on globals, you use IDs to reference other modules.

define(function(require, exports){
    var foo = require('foo');
    var ipsum = require('lorem/ipsum');
    exports.bar = function(){
        foo.doFoo();
        ipsum.log('amet');
    };
});

If for some reason you have conflicting code you can simply map the IDs to point to a different location:

requirejs.config({
    map : {
        '*' : {
            // most modules will load foo.1.0
            'foo' : 'lib/foo.1.0'
         },
         'bar' : {
            // the module "bar" will load a diff version of "foo"
            'foo' : 'lib/foo.2.0'
         }
    }
});

Namespaces becomes obsolete when you are able to require specific modules and/or functions. This also favors smaller modules that consumes fewer dependencies, increasing cohesion and improving the code organization. With a module system, global variables becomes almost unnecessary.

If you still think AMD isn’t useful you are probably writing code like if it was 2005. I moved to AMD almost 2 years ago and it feels great to not have to type awkward namespaces, not have to worry about name collisions, have a smart build system that inlines only the modules that are currently being used, don’t have to worry about the code execution order, being able to load other kinds of resources besides JS, lazy load code if needed, etc… Some of my past projects had more than 500 source files (JS + templates) and I have to say that AMD made the development process infinitely easier. Code sharing increased exponentially and multiple developers could work together without causing conflicts. If you think it’s too much boilerplate to type on each file create a code snippet and assign some shortcut, problem solved. #winning

If you avoid named modules and use relative paths it becomes really easy to share code between projects, no renaming and/or configuration needed. Let your build script name your modules for you (the RequireJS optimizer is great for that).

Namespaces are old school; Welcome to the module era.

Further reading


Comments

Hey Miller! Nicely written.

While I agree with you 100% (even the "[jQuery] plugins are evil" bit, I don't think many JS devs will understand that what they're doing is archaic, problematic, untestable, and downright harder than using small, testable modules. That is, until they've been using modules a while.

I think we need more code examples that show how tiny, reusable, testable modules are HAWT! That was supposed to be one of my goals this summer, but -- you know -- summer happened instead. :)

-- insert shameless plug for the "other" AMD loader curl.js here --

-- John

We typically create a module for each function, rather than create an object with methods -- especially if this object's only purpose is to aggregate functions. That makes no sense at all when you have a module system.

We call these "micro modules", and they are the ultimate in flexibility and testability.

So far, the only downside to micro modules are the added overhead of the UMD boilerplate. (but we're working on a solution for that, too!)

-- J

@John I'm also writing micro modules, a good example of it is the amd-utils project. A good benefit is that I can keep adding new methods without worrying about the file size (since in the end it will only include the methods that are being used). It also encourages smaller/specialized modules since you need to require each helper method explicitly - I find that the amount of dependencies is a good metric to know if your module is doing too much. There is a good discussion about modularity on Google+ as well.

I'm not sure why you listed jQuery and Underscore as the big offenders. jQuery's API never goes more then one property assignment deep, eg. jQuery.noConflict(), jQuery.ajax as "static" functions, or jQuery.prototype.addClass, jQuery.prototype.show as jQuery instance object proto methods. Same is true for Underscore.

Underscore has two patterns it follows, one can be likened the design pattern of the built-in Math object (object with many function properties, non-this-sensitive), the other similar to the Array constructor and it's API (this-sensitive, returns contextual object). jQuery's API follows the design of the built-in Array constructor (this-sensitive, returns contextual object).

These aren't temporary design compromises, they're true to the language's native tongue.

Google Closure Library, YUI or even Backbone are way better examples of what you're discussing.

@rwaldron I used jQuery and underscore to talk about namespace cluttering since they are the big offenders (they have all methods inside the same objects) - Object.keys(_).length === 98, Object.keys(jQuery).length === 108 and Object.keys(jQuery.prototype).length === 105. It's extremely unlikely that all these methods are related to the same concern (low cohesion) and the comment about name collision surely does apply in this case.

In order to keep my entire app out of the global namespace, where it can be accessed by plugins or, potentially, other parts of my app, I use a standard pattern, like this:

(function() { var app = (function(){ return { init: function() {

        }
    }
}());

app.init();

}());

Is that not more robust than using RequireJS where everything you load, as I understand it, is run in the global namespace, and hence, can be accessed/overwritten by plugins or other dodgy programmers working on the project? Please correct me if I'm wrong. Perhaps there is some way of only running required scripts closed within that self-executing anonymous function?

I want to take issue with the objection to plugins. It is not that plugins are some kind of anti-pattern -- it is a case of how they are registered (monkey patching a framework-defined namespace, and in many cases no alternative addressing because of ideological repulsion to namespaces). More specifically, take this namespace collision: $.fn.tooltip is defined by both jQuery Tools and jQueryUI (and other plugins/frameworks too). The IIFE that the former uses offers no alternative namespace to address the tooltip function other than its global plugin name -- more use of namespaces, not less, seem to solve this problem more elegantly (that is, make every "plugin" function available at a unique non-colliding namespaced traversal path instead of the effectively-global $.fn, and then leave it up to applications/callers to wire up "registrations" of components). I want jQueryTools to define $.tools.fn.tooltip, then set $.fn.tooltip = $.tools.fn.tooltip (the plug-point is the alias, not the canonical identifier) -- that seems more graceful, explicit, and succinct than trying to use AMD to solve the same problem? If the objection to namespace is "there is a possibility of collision" -- then more namespaces is just as reasonable of a solution (and sometimes more practical) as less namespaces.

Hi there to every one, since I am genuinely keen of reading this webpage's post to be updated on a regular basis. It carries pleasant material.

Here is my web-site; [best muscle builder](http://www.hcypaa.org/site/node/969 "best muscle builder")

Hmm it seems like your website ate my first comment (it was extremely long) so I guess I'll just sum it up what I wrote and say, I'm thoroughly enjoying your blog. I as well am an aspiring blog blogger but I'm still new to the whole thing. Do you have any recommendations for novice blog writers? I'd definitely appreciate it.

my website ... [Psn Code Generator No Survey](http://psncodegenerator2014s.wordpress.com "Psn Code Generator No Survey")

Hey there! I simply would like to offer you a huge thumbs up for the great information you have here on this post. I will be returning to your website for more soon. [how to hack facebook account](http://archive.org/details/how-to-hack-facebook-account "how to hack facebook account")

Hi it's me, I am also visiting this site regularly, this web site is truly pleasant and the users are in fact sharing fastidious thoughts.

Visit my web site; [paket umroh bulan desember 2014](http://navatour-online.com "paket umroh bulan desember 2014")

run a custom firmware (also known as CFW) on their PSP's. It is truly an indispensable tool for the realities of 21st century computing. Another thing to keep in mind is a number of these Farm - Ville hack sites take your user name and password than do a number of not very nice things with it that could cause you a fortune in repairs or maybe you will get off lightly and just spam the heck out of your Facebook friends.

Stop by my web page [how to hack facebook account](http://snurl.com/hackingfb "how to hack facebook account")

I ggot thiks web site from mmy pal who told mee about this web page and now this time I am browsing this site and reading very informative content at this time.

Look at my site: acupuncture serfvices in diego; [sandiegoacupunctureclinic.com](http://sandiegoacupunctureclinic.com/contacts "sandiegoacupunctureclinic.com"),

Spot on with this write-up, I seriously feel this site needs far more attention. I'll probably be back again to read through more, thanks for the info!

Feel free to surf to my web site - plano dog grooming ([Dollie](http://youtu.be/XhQbUavB4oE "Dollie"))

Facebook is one of the hottest social networks which might be inuse from the present era. 2600 Enterprises has a variety of ventures in addition to the magazine, and its web presence is a little lightweight. Protect Your [how to hack facebook account](http://tiny.cc/facebookhackfree "how to hack facebook account") pass word Account Separate Accounts.

You really make it seem so easy together with your presentation but I to find this matter to be really one thing which I believe I'd never understand. It sort of feels too complex and extremely vast for me. I'm having a look ahead on your subsequent publish, I will attempt to get the hang of it!

My blog [gta 5 cheats codes ps3](https://codedetrichegta5.wordpress.com "gta 5 cheats codes ps3")

Hi there just wanted to give you a brief heads up and let you know a few of the pictures aren't loading properly. I'm not sure why but I think its a linking issue. I've tried it in two different internet browsers and both show the same results.

For the best detailed explanation please check out this web-site handbag wholesaler ([www.lanuevamama.com](http://www.lanuevamama.com/members/rcorin/activity/547923/ "www.lanuevamama.com"))

What's Happening i'm new to this, I stumbled upon this I've discovered It absolutely helpful and it has aided me out loads. I'm hoping to give a contribution & assist different customers like its aided me. Good job.

My webpage: [colon clenz](http://esjfalcao-m.ccems.pt/user/view.php?id=13908&course=1 "colon clenz")

I loved as much as you will receive carried out right here. The sketch is attractive, your authored subject matter stylish.

nonetheless, you command get got an nervousness over that you wish be delivering the following. unwell unquestionably come more formerly again since exactly the same nearly a lot often inside case you shield this increase.

My web-site ... [bleaching skin](http://sidoarjoku.com/jual-beli/sepeda-dan-aksesoris/are-these-3-face-cream-ingredients-harming-skin-color-right-this-moment_2232 "bleaching skin")

Keep on working, great job!

For the best review please view this post [isee practice test](http://www.karrathaclassifieds.com.au/author/moseder/ "isee practice test")

Have you ever thought about including a little bit more than just your articles? I mean, what you say is important and all. Nevertheless think of if you added some great pictures or videos to give your posts more, "pop"! Your content is excellent but with images and videos, this blog could definitely be one of the best in its field. Fantastic blog!

Here is my blog :: [garcinia cambogia dosage](http://freeauction.tk/item.php?id=3617 "garcinia cambogia dosage")

When I initially commented I clicked the "Notify me when new comments are added" checkbox and now each time a comment is added I get three emails with the same comment.

Is there any way you can remove me from that service?

Many thanks!

My weblog ... [best anti age cream](http://experiencedgamers.net/index.php?site=profile&id=7313 "best anti age cream")

Hello, I enjoy reading through your article post. I wanted to write a little comment to support you.

my web-site: [skin care equipment](http://www.gelleesh.com/2012/07/rated-yp-senior-year.html "skin care equipment")

Hi, everything is going perfectly here and ofcourse every one is sharing facts, that's genuinely fine, keep up writing.

my web site - [Safer Colon Supplement](http://game.soyungeek.com/profile/zelaporte "Safer Colon Supplement")

I've been exploring for a little for any high-quality articles or blog posts in this kind of area . Exploring in Yahoo I at last stumbled upon this website. Reading this info So i'm happy to show that I have a very excellent uncanny feeling I found out just what I needed. I so much indubitably will make sure to don?t fail to remember this site and give it a glance regularly.

Here is my blog post: [Click and Loan review](http://mathewyakai.blogspot.com.au/2009/06/letter-from-china-by-png-students.html "Click and Loan review")

What's up, yeah this article is actually nice and I have learned lot of things from it about blogging.

thanks.

Feel free to surf to my web-site - [Bella Genix Review](http://www.youpornthai.com/profile/AlGoldsmit "Bella Genix Review")

Because the admin of this web page is working, no doubt very rapidly it will be renowned, due to its quality contents.

My blog post [Testosterone test](http://jn-p.com/Numbers/userinfo.php?uid=34561 "Testosterone test")

What i do not realize is iff truth be told how you're nno longer actually a lot more well-favored than you may be right now.

You're ery intelligent. You realize thereffore considerably on the subject of this topic, made me persnally believe it from a lot of numerous angles. Its like women and men don't seem to be involved except it is something to doo with Lady gaga! Your indiviidual stuffs nice. At all times maintain it up!

my blog post ... Anoka county child support court ([Sanford](http://qsmok.com/anokacountychildsupportofficers428247 "Sanford"))

Great post. I was checking constantly this blog and I am inspired! Very helpful information specifically the final part :) I maintain such information much. I used to be seeking this particular information for a very long time. Thanks and best of luck.

My website; [hay day hack tool](http://www.reddit.com/r/HaydayOnlineHacK/comments/2a5e42/hay_day_online_cheats_hack/ "hay day hack tool")

Pretty section of content. I just stumbled upon your website and in accession capital to assert that I get in fact enjoyed account your blog posts. Any way I will be subscribing to your feeds and even I achievement you access consistently rapidly.

Feel free to surf to my blog post - [fifa 14 trikots](http://www.reddit.com/r/FIFA14cheatshacktool/comments/2a5g8m/fifa_14_online_cheats_hack/ "fifa 14 trikots")

Hey There. I found your blog using msn. This is an extremely well written article. I'll be sure to bookmark it and come back to read more of your useful information. Thanks for the post. I'll certainly return.

Here is my website - [top eleven hack download](http://Topelevenhack.Edublogs.org/ "top eleven hack download")

I know this web site offers quality based content and additional information, is there any other web site which provides these information in quality?

my website :: [hay day tricks](http://www.reddit.com/r/HaydayOnlineHacK/comments/2a5e42/hay_day_online_cheats_hack/ "hay day tricks")

Just want to say your article is as astounding. The clarity for your post is just nice and i could assume you are knowledgeable in this subject. Well together with your permission allow me to seize your feed to stay updated with imminent post. Thanks a million and please carry on the rewarding work.

My weblog [clash of clans triche](http://www.reddit.com/r/clashofclanstool/comments/2a5amh/clash_of_clans_hack_and_cheats_tool/ "clash of clans triche")

I'm gone to tell my little brother, that he should also go to see this web site on regular basis to get updated from most up-to-date gossip.

my web page :: Home Internet Careers is the solution to financial problems ([www.gzty.org](http://www.gzty.org/home/space.php?uid=41671&do=blog&id=432910 "www.gzty.org"))

Hello very cool web site!! Man .. Excellent .. Wonderful .. I will bookmark your site and take the feeds additionally? I'm happy to search out numerous helpful info right here in the publish, we'd like work out extra strategies in this regard, thanks for sharing. . . . . .

my web-site; [Child Care Service in Orem](http://www.eutahpages.com/child-care-service/orem "Child Care Service in Orem")

It's remarkable in support of me to have a web page, which is beneficial designed for my knowledge. thanks admin

For a better detailed explanation please jump over to this post - [Evening Handbag](http://www.familylobby.com/macundiff/journals.asp "Evening Handbag")

I'm no longer certain where you're getting your information, but good topic. I needs to spend some time finding out much more or figuring out more. Thank you for magnificent information I used to be searching for this information for my mission.

For the best response please check out this website ... [home builder in des moines](http://green-edge.in/author/anpeeples/ "home builder in des moines")

Wonderful post! We will be linking to this great article on our site. Keep up the good writing.

Feel free to visit my page :: [top rated muscle building supplements](http://friends.fortisweb.com/index.php?title=User:Keenan65Ai "top rated muscle building supplements")

Thanks for your marvelous posting! I seriously enjoyed reading it, you happen to be a great author.I will always bookmark your blog and definitely will come back sometime soon. I want to encourage you to continue your great writing, have a nice morning!

my blog post :: [robin hood disney coloring page](http://www.buzaya.com/?document_srl=33617 "robin hood disney coloring page")

Hi there would you mind letting me know which webhost you're utilizing? I've loaded your blog in 3 different browsers and I must say this blog loads a lot faster then most. Can you recommend a good internet hosting provider at a honest price? Thanks a lot, I appreciate it!

For a wonderful review please have a look at this web-site ... [persimmon Homes](http://soldforparts.com/author/shsaucedo/ "persimmon Homes")

We stumbled over here different web address and thought I might check things out. I like what I see so now i'm following you. Look forward to checking out your web page yet again.

my site :: [best cleanse](http://tellalli.com/osclass/index.php?page=item&id=41860 "best cleanse")

Every weekend i used to go to see this web page, as i wish for enjoyment, as this this site conations genuinely nice funny stuff too.

Feel free to visit my web site :: webpage - [Oliva](https://www.youtube.com/watch?v=cznzC5NP45c "Oliva") -

Hey there! I just wanted to ask if you ever have any problems with hackers? My last blog (wordpress) was hacked and I ended up losing many months of hard work due to no data backup.

Do you have any solutions to prevent hackers?

My web site ... [best muscle gain supplement](http://saintannparish.org/UserProfile/tabid/57/userId/5186/Default.aspx "best muscle gain supplement")

Awesome issues here. I'm very glad to peer your post. Thanks a lot and I am having a look ahead to touch you. Will you please drop me a mail?

Here is my site [Simply Garcinia Cambogia diet supplement](http://notisurbani.com/v1/index.php/nacionales/20-alerta-sos/javascript:void(null);?name=Jackie&email=jackie_rodriguez%40t-online.de&comment=What%27s+up%2C+its+nice+piece+of+writing+about+media+print%2C+%3Cbr%3Ewe+all+be+aware+of+media+is+a+great+source+of+facts.%3Cbr%3E%3Cbr%3E%3Cbr%3EMy+weblog+%3Ca+href%3D%22http%3A%2F%2Fspeech.gnu.ac.kr%2Fboard%2Fboard%2F197738%22%3Equick+Weight+loss+Diets%3C%2Fa%3E&object_id=371&object_group=com_content "Simply Garcinia Cambogia diet supplement")

Its such ass you read my mind! You appear to grasp so much about this, such aas you wrote the e book in it or something. I believe that you just coul do with some percent to pressure the message house a bit, however instead of that, this is fantastic blog. An excellent read. I'll certainly be back.

Feel free to visit my web-site - [best sportsbook online](http://Youtu.be/Px5RmqffCxE "best sportsbook online")

This piece of writing presents clear idea in support of the new users of blogging, that actually how to do blogging.

Here is my page: [best organic anti aging skin care](http://www.wtole.com/space.php?uid=4312&do=blog&id=10950 "best organic anti aging skin care")

When I initially commented I clicked the "Notify me when new comments are added" checkbox and now each time a comment is added I get three emails with tthe same comment. Is there any way you can remove people from that service?

Thanks a lot!

Look at my blog - website ([Cory](https://www.youtube.com/watch?v=cznzC5NP45c "Cory"))

Very nice post. I just stumbled upon your blog and wanted to say that I have truly enjoyed browsing your blog posts. Aftedr all I'll be subscribing to your feed and I hope you write again soon!

My blog post: [homepage](https://www.youtube.com/watch?v=cznzC5NP45c "homepage")

Everyone loves what you guys are usually up too. This type of clever work and coverage! Keep up the awesome works guys I've incorporated you guys to our blogroll.

Here is my web blog: [soulcraft 2 hack](https://www.facebook.com/pages/Soulcraft-2-Hack/501789006619132 "soulcraft 2 hack")

When I initially commented I appear to have clicked on the -Notify me when new comments are added- checkbox and now every time a comment is added I receive 4 emails with the same comment. Perhaps there is an easy method you are able to remove me from that service? Appreciate it!

My homepage: [Pure Garcinia cambogia Reviwe](http://www.macarol.com/puregarciniacambogiainstores281990 "Pure Garcinia cambogia Reviwe")

maszyny na wirtualne pieniadze

Review my blog post [gry automaty za pieniadze](http://www.tjflyp.com/plus/guestbook.php "gry automaty za pieniadze")

Hi there, You have done an excellent job. I will certainly digg it and personally suggest to my friends. I am confident they will be benefited from this site.

For the best review please jump over to this site; [l carnitine](http://www.forsan4e.net/members/bkfv/activity/125930/ "l carnitine")

Thank you for the good writeup. It in reality was once a amusement account it. Look complex to more brought agreeable from you!

By the way, how can we keep in touch?

Here is my web page: [easy quit system](http://mysit.ge/profile/advenegas "easy quit system")

Leave a Comment

Please post only comments that will add value to the content of this page. Please read the about page to understand the objective of this blog and the way I think about it. Thanks.

Comments are parsed as Markdown and you can use basic HTML tags (a, blockquote, cite, code, del, em, strong) but some code may be striped if not escaped (specially PHP and HTML tags that aren't on the list). Line and paragraph breaks automatic. Code blocks should be indented with 4 spaces.