A case against the module design pattern

by Jason on November 28, 2013

The module design pattern is a particularly popular design pattern used in JavaScript these days.

The main reasons for its use are:

  1. “Private” variables via closure
  2. Global imports

A simple example of a module design pattern implementation looks like this:

var MODULE = (function(args) {
var _private_variable = null;
var _private_method = function() {};

this.public_variable = null;
this.public_method = function() {};

This is a very common pattern among JS devs but it is quite problematic.

The main issue is that it’s impossible to test any of the non-public methods. A common argument to this is that private methods shouldn’t be tested.

My argument against the module design pattern is this:

1. Your code is visible by anyone at any time. You’re not protecting anything. If you’re using JS to store sensitive information (encryption keys, for instance) then you’re out of your mind.
2. You limit the testability of your code
3. If you don’t follow a solid coding guideline then it could be difficult for new engineers to parse your code.

The module design pattern can be useful if private methods/variables are used sparingly and for the right reasons.