Revealing Module Pattern

495 views
Skip to first unread message

Welsh Harris

unread,
Feb 23, 2014, 10:44:13 AM2/23/14
to comm...@googlegroups.com
Does anyone see any drawbacks to this pattern?

Similar to the revealing module pattern.  I like this because as I write my code everything is private.  Then when I'm done I decide what to make public.  Also, that last code block serves as a kind of documentation to quickly see what will be public.

var publicVar,
    privateVar;
    
publicVar = "Hello!";
privateVar = "Hidden";

function add(num1, num2) {
    return num1 + num2;
}

function subtract(num1, num2) {
    return runSubtract(num1, num2);
}

function runSubtract(num1, num2) {
    return num1 - num2;
}

//public
exports.add = add;
exports.subtract = subtract;
exports.publicVar = publicVar;

Alexandre Morgaut

unread,
Feb 24, 2014, 4:13:21 AM2/24/14
to comm...@googlegroups.com
You shouldn't use publicVar as a local variable if it is not an object or if it is not exposed as read-only
Primitive values are assigned to properties by copy while objects are by reference...
 
In your example, publicVar is only initialized by the module so you won't actually have a bug but it could have been safer to directly initialize exports.pubicVar to prevent issue once a contributor start to use publicVar internally instead of exports.publicVar

Otherwise, I like your pattern with a dedicated "export API" section, that I also happen to use
To fix the mentioned issue, you may move this section to the top. Because of hoisting, it would still work for your exposed functions, and primitive public values would be initialized directly in the right place

Welsh Harris

unread,
Feb 28, 2014, 11:50:00 AM2/28/14
to comm...@googlegroups.com
Ah!  Thanks Alexandre, makes sense.
Reply all
Reply to author
Forward
0 new messages