Sunday, July 6, 2014

Definitive Module Pattern

When it comes to design patterns in javascript, the Module Pattern currently exists in two forms: (1) The Original Module Pattern, and (2) The Revealing Module Pattern. Today, I present a third version of the Module Pattern. What I call the "Definitive Module Pattern". https://github.com/tfmontague/definitive-module-pattern

Design Patterns

If you're still using the javascript prototype pattern, you're a little out-dated. Repetitively using "this" and "prototype" is not a great way to write javascript code.
function module() {
    this.public = function () {};
};
Several other Javascript design patterns exist (e.g. Module, Singleton, Flyweight, and more), and should be used where appropriate. Addy Osmani at Google has done a great job in classifying various Javascript design patterns (as documented in his book Learning Javascript Design Patterns). One design pattern not found in his book, however, is the "Definitive Module Pattern" - mainly because I just created it (or so I believe) about half-an-hour ago.

A common alternative to the prototype pattern, is the module pattern.

Module Pattern

var module = (function () {

    // private subroutines
    var private_one = function () {};
    var private_two = function () {};

    // public subroutines
    return {
        public_one: function () {
            private_one();
        },
        public_two: function () {
            private_two();
        }
    };

})();
However the original and revealing Module pattern, has some "code smell".

Definitive Module Pattern


The "Definitive Module Pattern" retains the advantages of the Module pattern (e.g. public and private scope), and the Revealing Module Pattern (i.e. not having to repetitively declare anonymous functions). Yet the pattern, offers the following advantages: decouples the Return statement from the "_public" subroutines, groups private and public subroutines into "_private" and "_public" object literals, and provides configurable public scope.
var module = (function () {

    // private subroutines
    var _private = {
        private_one: function () {},
        private_two: function () {}
    };

    // public subroutines
    var _public = {
        public_one: _private.private_one,
        public_two: _private.private_two
    };

    return _public;

})();


Tim Montague
7/6/2014