Monday, May 4th, 2009

No love for the module pattern?

Category: JavaScript

There was a cheer when Doug showed people that the module pattern could nicely give you somewhat “private” access in JavaScript.

At least, the Java folk definitely cheered.

Jonathan Snook on the other hand has no love for the module pattern and, after using it for some time, now avoids it:

Avoiding the Module Pattern makes debugging easier.

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.

Make extending easier

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

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.

This is going to be contentious, with people feeling one way or another. There is certainly value to the pattern, but maybe it isn’t the right choice for every team? What do you think.

Posted by Dion Almaer at 6:22 am
17 Comments

++---
2.6 rating from 38 votes

17 Comments »

Comments feed TrackBack URI

If he needs to extend, why not add a method that will do so? Have your module accept a function that it can then bind internally and expose what was passed. Problem solved. This could work for the debugging problem too if the exposed “extend” function can overwrite already existing methods. The purpose of the pattern is to make public, private and privileged areas, just because you can’t just sit there and override that at the drop of the hat doesn’t make the language unmalleable , in fact I could argue that it would make this pattern robust.

Comment by TNO — May 4, 2009

I’m a java folk and I like it. However, I don’t use the the module pattern for classic inheritance’s sake. I use it for code organization basically. Why would you try to do object hierarchies in Javascript? It’s simply the wrong language for it. I get much more mileage out of js simply passing functions (some stateful, some scoped, some not) around.

Comment by ilazarte — May 4, 2009

One enduring criticism of the Javascript Module pattern is that it dramatically increases construction time and memory use, as every object includes a fresh copy of the instance methods, which must be created anew during initialization and then maintained in memory for the object’s whole lifecycle. These aren’t insurmountable problems, but they are a reminder that the semblance of member privacy in Javascript always comes at a cost.
Snook’s debugging problem isn’t exactly a showstopper either, but it too serves as a reminder — by enforcing strict OO data hiding, you are fighting the language and its natural constructs. It remains possible, but there are consequences.

Comment by henrah — May 4, 2009

I don’t like the module pattern. I do like making a namespace per project and making my functions be part of the namespace. My goal, always, it to have my only global be that one namespace object.

Comment by Nosredna — May 4, 2009

@henrah & @ilzarte: How is enforcing strict OO data binding in prototypical inheritance fighting the language? Everything in JavaScript is an object–Functions, Arrays, Strings, Dates, Numbers. By using closures, it is possible to make a persistent local variable: i.e. a “private” variable. Extending objects by making a new object’s prototype property another object makes it possible to reuse code and properties from the parent object: a.k.a. inheritance. Is the syntax as simple as it is in Java? No. But to say that using OO in JavaScript is fighting the language or that it is the wrong language for it because the syntax isn’t easy is unfair.

As far as inheriting private properties and methods, one, if you have a method or property that you want to inherit, perhaps you want an “intenal” propety or method instead, as truly private members are only really scoped to the class and all instances of that actual class, and not children. In order to do this you need getter methods for all the internal properties or methods you wish to inherit, and you need to use private variables in the inheriting class to set them to the prototype’s inherited properties. For Example:

var ParentClass = function(){
var inheritedMember = ‘foo’;//inherited member of a child class.
var privateMember =’bar’; //private member that will not be inherited
this.getInheritedMember = function(){return inheritedMember;};
};
ParentClass.prototype = (function(){ return new Object();})();
var ChildClass = function(){
var inheritedMember = ChildClass.prototype.getInheritedMember();//inherits the parent member directly
this.useInheritedMember = function(){
alert(inheritedMember);
};
}
ChildClass.prototype = (function(){return new ParentClass();})();

var test = new ChildClass();
test.useInheritedMember();

Is it easy? No. You have to remember the members you want to inherit for each class. If you override an inherited member, you also have to override the getter method for that member. If you are inheriting a large number of internal properties, the inherited members and getters can take up a lot of space. Also, since the getters are public and JavaScript is a dynamic language, they can be overwritten at runtime. But it is definitely doable, and keeps your internal methods and properties from being accessible outside the class structure.

Comment by Jaxon — May 4, 2009

There is a large practical effect of having strictly enforced private fields and methods – obfuscation and dead code removal. A non-private field basically says “I am publically exported, do not munge me!” This means Javascript deployment tools are unable to rename the field or remove it if it can be proved inaccessible, because it’s name must be assumed to be stable for late binding later (e.g. third party usage)

This may not matter for small apps, but for large Javascript applications, something like GMail or Spreadsheets, it makes a large difference. This is one reason why GWT is so effective at creating packed code.

Comment by cromwellian — May 4, 2009

@Jaxon: that’s why we have libraries like Mootools and Prototype to ease the “use javascript as a classic OO language” model.
.
I personally prefer to take the best of both worlds, create extensible objects/classes (with POJ/Mootools respectively) and use closures for UI management where creating a class or object is not the correct path to follow (and I say closures in general, as using the Module Pattern is not always needed for every use case).

Comment by gonchuki — May 4, 2009

@Jaxon: “Everything in JavaScript is an object” You are wrong: var a = “ajax”; “a” is not an object. It is a primitive string. It has no properties, no methods.
This: ParentClass.prototype = (function(){ return new Object();})(); is equal to this: ParentClass.prototype = {};
There are no private properties in JavaScript, as well as there no real inheritance in JavaScript, but you can play “pretend”.
Most of the time you can find nice JavaScript way of doing something without pseudo-inheritance.

Comment by DmitryBaranovskiy — May 4, 2009

I love the module pattern (aka the javascript “Singleton pattern”). When you honor the pledge to not clutter the global scope, you have a choice: either package your code using the module pattern or declare every function prefixed by your namespace global. That gets hard to read, and it makes everything public, so how then are you to know which of these functions gets called by other scripts without doing a global search on every single one of them. Nay, the module pattern solves all the problems and is not hard to debug. Just because Firebug doesn’t display a private variable doesn’t mean you can’t type it in the “watch” field and get its value.

Comment by sonofman — May 5, 2009

@DmitryBaranovskiy: Strings *have* properties (“a”.length) and methods (“a”.toUpperCase()). And JS *has* inheritance — it’s just not classical inheritance but prototypical.

Comment by lunes — May 5, 2009

Hi

I find that this singleton better is far easier to use.

var MySingleton = new (function() {
this.public = “i’m public”;
var private = “i’m private”;
});

Much simpler and cleaner. I found this on http://nortools.blogspot.com/2008/06/my-javascript-patterns.html

Cheers
Adam

Comment by Adoro — May 5, 2009

Oops, I should have said “pattern” as opposed to “better”.

Comment by Adoro — May 5, 2009

Thanks Adam! ‘m fascinated by this notation :)

Comment by sixtyseconds — May 5, 2009

@DmitryBaranovskiy, primitives are “not 100% Objects” but inherit from their own constructor prototypes. In JavaScript Object.prototype is not instanceof Object but in any case, I will never understand why so often Java/C#/whatever developers think that in JS inheritance is bad … if we do not get prototypal inheritance it cannot be a language problem, don’t you agree? Finally, module pattern is useful when you need it, if you program everything with module pattern I agree there is something wrong. But, when we need it, what’s wrong with this?

function Module(name){

// privileged
this.getName = function(){
return name;
};

};

Module.prototype = new function(){

// private methods
function private(){
return [
"asked for", this.getName(), ++_times, "times"
].join(" ");
};

// private vars
var _times = 0;

// public methods
this.ask = function(){
return private.call(this);
};

// public vars
this.constructor = Module;

};

var m = new Module("pattern");
m.ask();
// asked for pattern 1 times

Comment by WebReflection — May 5, 2009

The module pattern makes my head hurt. :-)

After having written a dozen of JavaScript library files and coming up with my own pattern for handling semi-private data, all the while making use of Prototype’s OO mechanism, plus failing to use and like the YUI library in its 3.0 development version…

I would rather avoid any extra headache at this point.

Microsoft with Novell and Mono just gave me another one a few minutes ago. Novell’s Miguel de Izaca announced Moonlight 1.9 beta and I installed it and went where I could find Silverlight demos and I could not manage to see any Silverlight content using Moonlight after some three tries. Just uninstalled Moonlight thinking “thank goodness JavaScript can help me with staying out of too much trouble”.

Comment by jpedrosa — May 5, 2009

I´m using the module pattern mostly. One reason that I missed in the other comments is that it allows for parameter checking in the public part and processing in the private part. I find this very useful, since for distributed projects you have a declarative part and a seperated processing part which makes it much easier to read.

Comment by FrankThuerigen — May 6, 2009

Surely the module pattern as a singleton is fine, used in manager functions and single instances where is the need for extension?

I use it all the time as it gives a clear definition of what is meant to be where. If you want to have many objects of the same class or extension etc use a different pattern.

If you want to declare private members of prototyped objects just prefix them with _ it’s not very hard to follow.

2Pence.

Comment by elGinge — May 7, 2009

Leave a comment

You must be logged in to post a comment.