Why I don't love JavaScript's Module Pattern

The Module Pattern is the use of closures to create, in essence, private functions that are only accessible by other functions created within that closure. Functions can be attached to an object and returned outside of that function call. This establishes a public API and only the functions defined within that public API will have access to those hidden functions.

The YUI blog documents this well but here is a simple example of the Module Pattern:

var ManageChildren = (function(){
    var children = [];
    
    return {
      addChild: function() { /* add to children array */ },
      removeChild: function() { /* remove from children array */ }      
    }
 })();

In this example, the ManageChildren object will have two methods: addChild and removeChild. From outside the wrapper function, you cannot access the children array that is defined within.

After having worked with and used this pattern for some time, I now avoid it.

Debugging

When it comes to troubleshooting a particular troublesome page, I like to crank open Firebug's console and play around willy-nilly. The ability to reshape objects lets me test theories before putting them into practice with real code. It also allows me to inspect things to make sure they're working as they should.

Going back to that example I just showed, what if you needed to determine the length of the children array? It's not exposed. Which means you have to insert logging code, or create a breakpoint. In either case, you're forcing a page refresh to re-execute the code.

Now imagine this code was minified and deployed to a live server. It works locally but stopped working on a live server. How much do you feel like trying to add logging code or breakpoints? (Try adding a breakpoint to minified code in Firebug.)

Avoiding the Module Pattern makes debugging easier.

Make extending easier

Another frustration I have with it is the difficulty in being able to extend that object. You can't just add additional functions onto it because you won't have access to the properties defined within.

Take a look at this attempt to extend our object:

ManageChildren.getLength = function(){
    return children.length;
 }

That won't work. Neither will this.children.length, or anything else you try, because children is a variable that's only available to any function declared within that closure.

Aspect-oriented Programming

One other trick with JavaScript that I sometimes like to take advantage of is similar to aspect-oriented programming. While aspect-oriented programming is a deep subject, the key thing I took away from it was the ability to append code before or after a function call. It feels like an event handler. Here's another fun example:

var oldChild = ManageChildren.addChild;
ManageChildren.addChild = function(){
    /* do what you need to */
    oldChild();
}

See what I did? I took the old function and replaced it with my own. Then I proceeded to call the old function. With the module pattern, though, I wouldn't have access to any of those hidden properties. I could never actually add an element to the children array because it's private.

JavaScript should be malleable

One of the features that attracts me to developing in JavaScript is the ability to manipulate objects so readily. As a result, the module pattern is something I try to avoid.

Published April 29, 2009
Categorized as JavaScript
Short URL: https://snook.ca/s/944

Conversation

45 Comments · RSS feed
Scott said on April 29, 2009

Yep, sometimes I want to modify or replace a method entirely on an object from within Firebug, or access some property from the console (or javascript: in the URL) to verify something; not having access to that would make life (in the development aspect) harder.

Nick Carter said on April 29, 2009

While I don't frequently use pseudo-private variables in JS, I appreciate their usefulness in soothing the worries of paranoid Java heads.

It does feel un-JavaScript, though, as you say. Less maleable than it should be. I feel the same about getters/setters in general. Unless you need a callback, a property is just fine.

Mark Perkins said on April 29, 2009

I'm not sure I entirely agree with you I'm afraid. Personally, I love being able to effectively have private and public methods, especially if others will be using the code. I find it good organiser.

However, it's certainly not the tool for all jobs, and I certainly don't see it as an all or nothing choice. Write the bits that need to be stricter about access etc using the module pattern, and use whatever you like for the rest. That's my general approach day-to-day.

Nate Cavanaugh said on April 29, 2009

I'm with you on this. How often do we need truly private variables.
If you're trying to hide something for privacy sake, at best it's only through obscurity, and it can eventually be figured out somehow.

IMHO, marking it as private with an underscore prefix is enough. That alerts the developer that modifying it isn't supported, but at least it's an option.

Ryan said on April 29, 2009

I'm very new to OOJS and js in general but couldn't you add a length function to the addChild's protoype to access the children array? Maybe this shows how green I am.

Jonathan Snook said on April 29, 2009

@Mark: Sure, it sounds cool but why do you need to protect them? Do you work on a team where people don't know what they should or should not touch? Is your code going out to a larger audience and they shouldn't have access to those properties? I was attracted to the idea at first but in practice, I've never found that I actually need it. JavaScript is open, it's readable. What's to stop people from copy/pasting the code into their own functions?

Eric Shepherd said on April 29, 2009

I'm a fairly heavy user of the module pattern, though I prefer to use the "revealing" variant where the return statement simply contains references to the private functions/properties that you wish to make public.

One hypothetical that I find this useful for (though it's actually a simplification of a real-world scenario, not exactly a hypothetical): Say, for example, that you have some sort of timer/interval property that affects some part of your application. There's a piece of logic that has to be run in order to set that property, since setting it to "x" is only allowed under certain circumstances. This piece of logic is performed by a setter function that encapsulates this logic. If the property can be changed directly, there's a chance that some implementor of your code later on will change it directly, bypassing the necessary logic and breaking some part of the application. When code's going to be around for a few years and implemented by many different people on different sites, I want the security of knowing that certain things can't just be changed by accessing a property directly.

Your point about adding methods to the object later is well-taken. However, I'd say in that case that you should simply make that property public, since future APIs apparently need to use it. Using the revealing module pattern lets you make private methods public easily, without moving code around, and provides and easy-to-read built-in documentation of what the public members of your object are.

Brad Harris said on April 29, 2009

It's great to hear your thoughts on this subject, and is one I feel similarly about. The benefit of restricting access to properties is by far less than the benefits you gain by keeping your objects truly open. If you're sending information to the browser, its not secure. If your javascript can cause harmful server side changes by being executed improperly, you have bigger problems.

Luke said on April 29, 2009

It depends on the audience for your code. In a mashup world, code that you write could be intercepted and modified with mal intent. In general I agree that truly hiding data should be kept to a minimum, and using the underscore convention is more appropriate to the medium.

Really it's just another tool in the tool chest that was unfortunately adopted like the shiney new hammer when it was publicized. We've all done it. You discover some new technique that registers high on the Nifty-meter and overuse it until you understand its particular application.

Jonathan Snook said on April 29, 2009

@Luke: if you code gets intercepted and can be injected, the last thing a hacker is going to care about is access to that private data. They'll just overwrite the object with its own info.

Joseph Scott said on April 29, 2009

Sticking with your example then, you'd use something like:


var ManageChildren = (function(){
    return {
      children: [];
      addChild: function() { /* add to children array */ },
      removeChild: function() { /* remove from children array */ }
    }
 })();

then? Another way to phrase your argument then would be to never use private variables.

I'm not ready to say I agree 100% on this, but the nature and environment of Javascript does seem to lend itself to exposing data instead of hiding/protecting it.

Andy Kant said on April 29, 2009

Although most of the time the module pattern is kind of a waste (easier just to prefix your "private" variables with an underscore to manage them), there are some times where it can be useful. I developed a database library a couple years ago that has a workaround for this issue (just a mechanism to expose internal variables to extensions/plugins), but it really serves no purpose aside from hiding data from accidental corruption.

The aspect-oriented programming concept is extremely useful though. I wrote a helper library that allows functions (along with entire classes) to be extended with the ability to inject prioritized preprocessors and postprocessors into every method. The database library uses this ability to implement a base set of functionality in order to simplify the code base (just basic data storage methods). By the use of the extension system, additional functionality can be added like validation routines while keeping the code base clean and organized. It is also pretty useful as you mentioned for adding custom event handlers (can be important when using third-party libraries).

Chris Wallace said on April 29, 2009

Honestly, I've never used the module pattern simply because I never needed it.

Todd Baker said on April 29, 2009

I think you all should check out this book: http://www.amazon.com/JavaScript-Design-Patterns-Recipes-Problem-Solution/dp/159059908X/ref=pd_bbs_sr_1?ie=UTF8&s=books&qid=1241041448&sr=8-1 . I'm sure Johnathan has, and just might be forgetting the power within it.

Using the singleton (thats the design pattern name, not module) has very a specific use: you use it when you want to create static methods not attached to an object, such as external API calls. Example: Think about having the URL to to your proxy call, hidden behind a private variable in a singleton, but exposing the the main function that makes the AJAX request, as a public function. It's good design.

If you'd like to be able to extend your objects, just do it the normal way, create a constructor and add methods to that object via the prototype object.

And being able to append code before or after a function call is powerful, I won't disagree there, but there's a design pattern that lets you do that. Its called the decorator pattern, and its truly very powerful if used the proper way.

So yes, I understand everyone's qualms about why they don't like using singletons, but they should be used for a couple of reasons:

1. They protect your code. We all know cluttering the global namespace is not a good thing and can lead to some very nasty debugging sessions. This problem grows exponentially once you start using 3rd party libraries.

2. Design patterns are universal. They allow other developers to talk about your code at a very high level and not have to worry about the implementation. This is VERY important when developing with a large group of devs (more than 4). They'll almost already know what the code is going to look like.

3. Simplicity. I've ran into many problems trying to add methods on the fly and keeping track of scope, what object has what, etc.

So, again, check out Dustin's book, and it'll give you a little bit better insight on when to use the singleton (module) and when to just use a normal plain object.

Jonathan Snook said on April 29, 2009

@Todd, thanks for a well though out reply. Allow me to rebuke your response.

1. I'm not talking about cluttering the global namespace. I'm talking about allowing all properties and methods of an object to be globally available. And in the world of JavaScript, all you're doing is protecting the code from yourself (or from your team, or from anybody else who's trying to do any of the things I mention above).

2. Design patterns exist but there's no reason they have to be used. A sign of a good developer is when they know when and when not not to use a design pattern. The module pattern, as defined, just describes code protection, something that I don't feel is critical. The fact that I want access to these properties is specifically because I'm worried about the implementation. I want to inspect it. I want to play with it. But you're throwing up roadblocks because of some adherence to a design pattern or some desire to protect your code.

3. Simplicity is a side effect of well thought out design. The module pattern doesn't solve that.

There may also be some confusion in what you think the module pattern does. While in this case, it may be used for a singleton, it could be used just the same for a class or object prototype. And that's another reason why the design pattern isn't clear.

var myObject = {
/* this looks like a singleton */
}

var myObject = function(){
/* this looks like a class */
}

As you can see from what I've shown, in neither case is the module pattern used but the implementation defines the pattern. That's more important.

Sean McArthur said on April 30, 2009

While I often mock Javascript's way of create pseudo-privates, I must disagree that private variables in Javascript are a bad thing.

In every other programming language you use, there are private variables, and you likely created some on classes you've made. Even if you haven't, the classes of the standard library have private variables.

The reason for making variables private isn't to make the variable unknown. The point is to make it a no-no to manipulate that variable directly. When one of your co-workers starts to interact with the code you've written, they'll see they can't interact directly with "children". With just an underscore or whatever, you're suggesting not to, but if some programmer feels he's smarter than you, and decides to manipulate it anyways, he may have broken it. This is the whole point of making variables private in any language. To stop fellow programmers (or yourself).

As I said, while I don't usually try to get private variables in my Javascript, some of your complaints are universal to private variables in all programming languages (globally unavailable, debugging, extending (other languages allow protected for that)).

Eric Shepherd said on April 30, 2009

Sean's point is what I was trying to say, only probably put better.

If there's a method that needs to determine how often to show an advertisement, for example, allowing that code to be bypassed could have pretty negative effects. Having a setter and keeping the affected variables private makes sure that the proper logic is always run through, rather than opening up the chance that later on, some developer who wasn't there when the code was written might accidentally (or intentionally) bypass the proper logic.

Ideally, you have unit tests that allow your public-facing code to be tested, and you select carefully what needs to be private. And hey, if nothing needs to be private in your code, fantastic. Never good to use a pattern for its own sake. But there are instances, especially on large teams with code that will be around a long time, where it is a good idea.

Karl G said on April 30, 2009

@Sean

Python doesn't actually have any form of private variables. The closest you can get is to double underscore a variable to get it name mangled, but it's still accessible. Despite this (and a lack of static typing), the world doesn't implode and Python programmers tend to get their work done without difficulty. There are a few Python libraries I've used where an underscore attribute was widely used. When this happens, the normal response is to either officially bless it or create a public api equivalent.

Since I come from that community, I have the opposite viewpoint. Making your stuff private is basically declaring yourself to be smarter than all the programmers using your code. Putting an underscore on the name is a warning sign to other programmers that they should not be touching, but it still gives them the option to touch. If they screw stuff up, it's their own fault. They were warned and so it's their problem. The only hindrance to you, the author, is that it's considered polite to deprecate when you know a semi-private variable is being used instead of just changing the api.

On the user side, I know that if I touch an underscore attribute in Python code it's my problem. At the same time, it's much easier than having to (monkey)patch the library and it lets me get something working while I complain on the mailing list.

Andy Hume said on May 01, 2009

I agree with you Jonathan, that it's a design tool and a good developer knows when to use the tool and when not to. However, in my experience there are times when this particular pattern is a useful one.

Any heavy JavaScript application developed by a large team could have hundreds of thousands of lines of code all being worked on at different times over the course of years by dozens of different developers. Not all of those developers understand the nitty gritty detail of specific parts of the codebase - *and they shouldn't have to*.

If I'd developed your ManageChildren module I'd have created a well designed and well thought-through (hopefully!) class that exposed a succint and understandable API to the rest of the application and the developers. If a developer some years down the line is able to come along and manipulate the children array directly (and if they can they will!) then this undermines the integrity of the whole ManageChildren module. It's no longer managing children. Outside factors are managing children as well, and the effects of that could ripple through the application in many unforeseen and difficult to spot ways.

This is nothing too profound I'm explaining here of course, it's the reason scopes exist in the first place. I guess my point is that the techniques are just as valid within JavaScript as they are within any other programming environment.

Frederico Caldeira Knabben said on May 01, 2009

Hey Jonathan, you should start writing a new article now, titled "Why I love JavaScript's Module Pattern", otherwise you will be missing a powerful feature in JavaScript programming.

Josh Johnston said on May 02, 2009

Hi Snook, I'm a big fan :)

What I got out of this post was to consider 'debugability' as a key trait of good software. Nice one.

And while I agree with your example, I don't think I've ever used the module pattern with the intent of hiding stuff (ie. private). Instead, it's more about namespacing, improving structure and readability of the code. Making sure that different parts of the app aren't stepping on each others toes.

So I'm curious - now that you and Module Pattern are on the splits, what's your preferred way to do namespacing?

Dave said on May 02, 2009

"Allow me to rebuke your response." -- I think you mean "rebut".

In any case, it depends on the code's audience: if you're creating an API for public consumption keeping things private is subject to the benefits and problems as in languages that support it in different ways. Deciding what to make "visible" in the API is part of API design regardless of the language.

cancel bubble said on May 02, 2009

Why not just add another public method to the object you're returning that returns the length of the array?

Jonathan Snook said on May 02, 2009

@Dave: you're right, rebut was the word I meant. Thank you.

Look at YUI, look at Prototype, look at Dojo. These are libraries with large APIs designed for public consumption. And yet their use of the Module Pattern, as described here and on the YUI blog, is near non-existent. (MooTools uses it for their Native class but then everything else doesn't; relying on mixins for class creation). Most use the underscore to indicate private properties or methods.

This is JavaScript, everything is visible. There's no hidden implementation, there's nothing to hide.

About the only argument I've seen that makes sense for using the Module Pattern is the ability to use closures to maintain variable scope instead of having to rely on call/apply (as normally implemented in a bind or bindAsEventListener method). But at the cost of debugability and extensibility, it's not worth it for me.

Nicholas C. Zakas said on May 02, 2009

It seems like your biggest complaint about the module pattern is that you can't debug in the way you would like. I'm not a module pattern fan by any means, mostly because I think it's overused by people who don't truly understand all of the implications. I also agree that, in most cases, notation should be enough to indicate "don't touch this," and believe that closures should only be used when other approaches fail.

That being said, I've not found the barrier to debugging the module pattern to be that tough. I rarely start debugging without loading the page since the code I'm interested in is typically affected by other operations that occur during initialization. If that's the major issue in terms of debugging, then I'm not sure it's really an issue at all.

And if you're worried about debugging in production with compressed files, take a look at an article I wrote a while back, Production JavaScript Debugging. I don't think the module pattern makes it any more difficult to debug compressed JavaScript.

I think the thing everyone should take into account when reading this article (and all opinion-based ones) is that development methodology and approach is often based on a series of requirements including functional ones as well as engineering ones. Developers will develop in such a way that it's most useful to themselves, so one person's approach isn't necessarily the only right way. Not using the module pattern isn't any "better" than using the module pattern in a vacuum, it only matters based on what your goals and preferences are.

Thanks for sharing, Jonathan.

Jonathan Snook said on May 02, 2009

@Nicholas: Thanks for pointing me to the Fiddler post on the YUIBlog. I probably skipped over it at the first mention of Fiddler because I normally use Charles for HTTP debugging. Thankfully, Charles up a similar feature, which I'll have to take advantage of.

Andy said on May 04, 2009

I'm a little confused about the argument...

If I understand you correctly your issue with the module pattern is that the variables you are interested in are not visible because they are not in the same scope. Then wouldn't you have the same issue with functions and (their) local variables?

Christoph Pojer said on May 04, 2009

The way I understand your article is that you don't like visibility at all. When you declare a method or a property as private (or protected) in a Class, in any OOP based language, you cannot access it from the outside when you want to know the length of the children array, for example. For me it feels good not to be able to modify something from about everywhere. It actually makes debugging a whole lot easier because I can narrow down where a change on a property happened - I know it can only come from inside the class :)

While it does not matter if a method is visible or not when you are working on implementational work for clients, visibility properties are very important when you are creating an API. As previously stated in the comments you don't want the users of your API to mess with private functions (or functions that are intended to be private, so to say). I'm going to round that up by saying that it is a rule of API design that you only get one chance to push out a solid API and after that you can never change it again. And if you expose just about everything people tend to use it, just because it is available - and then you can never change it again. That sucks. I think I'm going to refer to MooTools here as we certainly don't want people to mess with the internal API. For the next major release that is why we try to make as much internal as possible by still providing a great API to hook in for extensions. This makes it also safer for us to not break existing code when we release an update. This probably is also the reason why from 1.11 to 1.2 so many things broke - everything was public, every script tried to hook in at any place but it was decided to recode the whole framework (as it always happens for mootools :D ) and make it more straightforward.

Anyway, lets get back: JavaScript is a special case where we don't have visibility available. That sucks. But its also cool. I'm mixed with that. Sometimes its just awesome to pass everything around, use any property from anywhere in your code and it maybe helps you while coding for a little problem. But in the end you end up having a big mess over your whole code. What I'm trying to get at is that it is really important when you create an API to think beforehand. In your example you need to think "Do I need to know the length of children? yes/no" and implement a getLength method or something like that on the object. When I have an object "ManageChildren" do I really need to access the children array? Isn't that what the object should be about? Thats fundamental API design - why access a property when the object is intended to take care of it?

I give you that this pattern makes extending in JavaScript harder, very hard indeed. Which rises the question if this isn't another API design question: If you know you need to extend the class and the children array must be available, you need to find a way to provide access to it - but this doesn't make the pattern a bad one. I'm repeating, its ultimately a design desicion. In my PHP code, for example, everything that is open to the user and possibly going to be subclassed is protected instead of private. I know we don't have protected in javascript at all but nor do we have abstract classes or a final keyword to express our feelings towards classes and methods ;)

(Also, for the sake of debugging, you could do it like this: http://paste.mootools.net/f21ef23c1 and just remove the privates property in production code)

Jonathan Snook said on May 04, 2009

@Andy: there's a difference between private variables/methods meant to be shared across an entire object and local variables to assist in the internal process of a given method.

In the latter situation, you can still replace the function and know that you'll still have all you need coming in and all you need to process what needs to go out. That's something you can't do in the former without rewriting the whole class.

Care should be made not to make your functions too large. I ran into this issue on a project where Scriptaculous' drag and drop implementation had quite a large implementation within a single function and required having to replace it entirely.

Scope is something we have to deal with at one level or another and I like to minimize how much gets gobbled up within a single scope.

Blago said on May 04, 2009

I guess there are two contexts that need to be considered:
1) You own and control the codebase.
2) You are using some sort of library written by someone else

In the first case, it's up to you to architecture your code in a way that will serve your needs best: add callbacks, custom events, class inheritance schemes, etc. JS is flexible enough to meet almost all your patter needs.

When you don't own the code... well get over it. Imagine jQuery gave unrestricted and indiscriminate access to it's internal state. Do you think it would've been as conflict-free and successful?

"Sure, it sounds cool but why do you need to protect them"
Because this is how you create an interface and control access. It becomes essential sometime after you write the first 1000-2000 lines. Especially when other people will be using it.

If you control access you can make assumptions about the internal state in your code. If you don't on the other hand, you have to plan for ANYTHING.

Given a large enough project, long enough time, and a decent employee turnover your code will be riddled by hacks and patches done by dozens of people with questionable understanding of what their predecessors have done. Believe it or not, most people have 1.5 hours to make that small change. They don't care how's coming next. They won't spend an extra 2 hours of their own time to do it "right".

As for debugging with FB... a page reload is a small price to pay.

chencheng said on May 05, 2009

I don't think debug is an powerful reasion. When js files is on remote server, you can replace them to local files with fiddler.

Nathan de Vries said on May 05, 2009

Hi Jonathan,

As you can see, this issue really polarises people. Douglas Crockford seems to be the biggest advocate of locking things down as much as possible, however even he will agree that with the current Javascript implementation we've got, it's *always* possible subvert those same security measures. Essentially, it's security by obscurity.

And I agree with you that these "obscurity" measures get in the way of the day-to-day development and debugging of Javascript. Declaration of public/private code is important to me, however it's only important in so far as the *intent* of its' use. Anything more than a declaration of intent just gets in the way of enjoyable Javascript.

Cheers,

Nathan de Vries

Kumar McMillan said on May 06, 2009

I agree that private variables should be avoided at all costs for debugging purposes but the problem with JavaScript is that everything is a global. I don't think it counts as the module pattern but best practice IMHO is to enclose all code per JavaScript file in an anonymous function.

That way you can be sure your code does not collide with anyone elses. For example, to rewrite your example:


(function(){

var oldChild = ManageChildren.addChild;
ManageChildren.addChild = function(){
    /* do what you need to */
    oldChild();
}

})();

This is the same except oldChild is no longer a global variable. This may not ever happen but it would really bite if someone else made a global named oldChild. ManageChildren is still global because var was not used. This allows for free debugging which I agree is important.

Jeremy said on May 06, 2009

The thing I don't get about the "obscurity" or "lockdown" or whatever you want to call it side is: how does the module pattern actually help achieve what it's supposed to achieve? In other words, everyone's argument for the module pattern seems to be "it prevents people from breaking code and creating bugs" ... but I don't understand how it does that.

Let's take two scenarios:
A) company that uses _fieldName to signify private fields
B) company that uses module pattern to enforce private fields

In A), a "bad" programmer can simply set _fieldName directly, instead of using the setFieldName method, and as a result some important logic might not get run.

In B), a "bad" programmer can simply expose _fieldName and set it directly rather than using the setFieldName method, and as a result some important logic might not get run.

So unless you're locking down your files such that no one can edit them after they've been created, the module pattern doesn't do anything for you. Either way, if a "bad" programmer wants to ignore your design and access private variables, they can. So (again, unless you lock down your files to prevent any changes) the module pattern does nothing but create problems.

It seems to me the only way to actually solve the kind of problems that the module pattern is supposed to solve is to implement peer reviews or similar policies; can anyone who supports the module pattern explain what I'm missing?

Nathan de Vries said on May 06, 2009

@Jeremy: In the case of B, it's difficult (but not impossible) for malicious code running on the same page to get a handle on _fieldName and observe or change the values. Making it difficult to access doesn't warrant the extra effort, in my opinion.

墨尔本 said on May 06, 2009

I think it's a problem about tomato and potato.
Everybody has his own choice.

Duncan Beevers said on May 07, 2009

By using the module pattern you can create clumps of behavior that you can then compose (typically using prototypal inheritance) to create new objects without worrying about property-name collisions.

For example, you may want to have an object that dispatches custom events. It's useful to put this behavior in a module and to extend that module when creating your own object. If you use direct property assignment you have to worry about name collisions with all of the 'private' properties of an event dispatcher when you really only care about the interface to the behavior.

On the other hand, private encapsulation makes it very difficult for users of your code to be able to easily instrument or customize it through userscripts.

I think the decision about when to use the pattern should come down to the intended audience and purpose for the code.

Jeremy said on May 07, 2009

@Nathan - Thanks, I hadn't considered the "somebody using Firebug (or whatever) to add their own JS" case. However:
1) it's not impossible in case A either; if you have:
var a = (function() {
var b = 5;
return { "add":function(){ return b++;};
}
it's true that I can't do "a.b = 12". However, I can do:
a = (function() {
var b = 12;
return { "add":function(){ return b++;};
}
so it's not "secure" either.

2) I think pretty much any well-educated web developer would agree: you should never rely on JS for any security whatsoever; you should always validate on the server-side. If you don't, you will ALWAYS be vulnerable to malicious JS injections.

So, it doesn't seem to me that the module pattern gives you any added "protection" either, except for just making the attacker have to copy/paste some of your original code ... unless I'm missing something (and again, I may well be).

Jeremy said on May 07, 2009

@Nathan I just realized I forgot to complete my examples; sorry about that. However, since we all understand how the module pattern works, hopefully you understood what I was saying.

Jeremy said on May 07, 2009

@Duncan Thanks for reminding me of the namespacing benefit of the module pattern; I really think it is the only benefit that is uniquely available only to the module pattern.

"I think the decision about when to use the pattern should come down to the intended audience and purpose for the code."

Indeed. But it seems to me that the only argument as to why the module pattern should be used for someone's particular audience/purpose is if they want to allow separate namespacing for certain blocks of code. The "it protects your code from your fellow coders" and "it protects your code from malicious injectors" arguments don't seem to actually hold any water (again, unless you're preventing your fellow coders from editing your files by some other mechanism, OR unless I'm missing something, which I may well be).

Crescent Fresh said on May 15, 2009

@Duncan: I totally agree.

I personally love the pattern for this reason:

function MyClass(domElement) {
// private state
var flag = 0;

function foo() {
// notice we don't need additional closures, apply(), call(), "var that = this;", etc
setTimeout(bar, 1000);
domElement.addEventListener('click', baz);
}

function bar() {
flag = 1;
}

function baz() {
domElement.removeEventListener('click', baz);
}

// public API
this.foo = foo;
// ... etc
}

That is: the pattern defines scope implicitly. Which is a real win for code that passes callbacks around to setTimeout or event dispatchers (custom or DOM based).

Note this is a terrible pattern for memory consumption and constructing large collections of objects.

Dan said on May 16, 2009

To me the only use for creating private members like that is, if you want to prevent people from messing with your code through means like Greasemonkey. Apart from that, i can barely see real use for this in Javascript.

The 2000 lines of code argument doesn't really fly with me, because i wouldn't want to publish a big app like that in an easily downloadable format like a .js file. I'd rather build that server-side. Unless you're building some freely available library for example.

Fini Alring said on June 23, 2009

A simple example of where private variables would be beneficial, could be an addChild() method that also does some logging or manipulation of the value. Or a removeChild() that does some extra garbage cleaning tasks. Now if a co-coder didn't notice these things and began to manipulate the children array directly this could manifest in problems down the line such as high memory consumption, incorrect logging and statistics etc.. Something that the co-coder might not discover during his hacking spree on the public array, and could result in hours and hours of debugging, so in a way privacy can be used to proactively avoid debugging too much ;).

I'm not using it much in JS, but there are reasons for public/private resources.

Mike McGranahan said on April 21, 2011

Blech. Rather than throwing out the baby with the bathwater, why not do something a little more sane, like driving the exposure of the internal state by configuration:


var myModule = (function _myModule() {
  var _privateState = { i: 0 };

  var result = {
    increment: function() {
      _privateState.i = _privateState.i + 1;
    },
    get: function() {
      return _privateState.i;
    }
  }

  if (isDebug())
    result.state = _privateState;

  return result;
})();

Implement isDebug however you want. It could look at a cookie, the url hostname, a token in the fragment identifier, some configuration mechanism, or can be populated statically or even be redefined in the javascript console. End result is that you can get to the normally-private state as a property on the module instance.

German Galvis said on May 19, 2011

When creating a rather complex object in javascript using literals i ran into the issue of constantly using "this" everywhere or passing it as scope (var self = this) for callbacks in jquery animations, for instance.

I adopted the module as a cleaner way to implement a set of methods/functions and reveal specific ones when needed, plus it have some degree of readability bonus, since when doing a handover of my code to other FED, the guys tend to get quickly which are the "main" things to take into account

Sorry, comments are closed for this post. If you have any further questions or comments, feel free to send them to me directly.