Javascript Encapsulation

19 Nov 2011. comments

In Douglas Crockford’s book “Javascript: The Good Parts” it discusses how to use encapsulation in Javascript. Since there’s no concept of private variables in JavaScript closures are used:

function createAdder() {
  
  var result = 0;

  return {  

    add: function(value) {  
      result += value;
      return result;
    }

  };  
    
}

var adder = createAdder();
adder.add(2);  // => 2
adder.add(42); // => 44

Here we’ve controlled access to the ongoing value through an interfacing method.

However, if you do a quick search on StackOverflow, you’ll quickly encounter a huge number of answers on javascript questions which say not to bother with private variables. Their reasoning is “well you can just look at the javascript source in the browser so what’s the point?”, as if to imply that security is the issue. This is missing the point.

One of the primary reasons to use encapsulation is to control the internal state of the object by only providing a limited interface. This protects the integrity of the state. In the previous example there is no way to deal with result except through the touch point that we expose. We can easily change the internal management of our object and consumers of the code need not care.

The purpose of encapsulation/information-hiding in any language is not about security protection from nefarious people. It’s abstraction. You shouldn’t need (or care) to know how the internals of an object are managed, only that there is an interface to an object that can be used to accomplish its advertised behavior. And the smaller the footprint of the interface the less complexity exists for the consumer to understand. You should expose no more than is necessary. If you do this you’ll have looser coupling and allow consumers to easily understand the APIs intent.

comments

Tagged: javascript encapsulation ocp abstraction

2017 Ben Lakey

The words here do not reflect those of my employer.