Javascript Encapsulation

After having read Douglas Crockford’s book “Javascript: The Good Parts”, I had learned some ways to leverage objects and information hiding, in the following manner:

var fooInstance = function() {
 
	var privateAlpha;
 
	return {
 
		getAlpha: function() {
			return privateAlpha;
		},
 
		setAlpha: function(a) {
			privateAlpha = a;
		}
 
	};
 
}();
 
fooInstance.setAlpha(10);
console.log(fooInstance.getAlpha()); //10
fooInstance.setAlpha(20);
console.log(fooInstance.getAlpha()); //20

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?”. This is missing part of the point.

One of the primary points of encapsulation is to control the internal state of the object, by only providing a limited interface. This protects the integrity of the state.

BUT… the other purpose of private variables and encapsulation in any language is not simply security or protection from nefarious people. It’s abstraction. An external entity should not need or care to know how the internals are accomplished. The smaller the footprint of the interface, the less complexity exists for the consumer to understand. You should expose no more than is necessary to leverage the functionality. The result of doing so is code that has looser coupling and is easier to understand by those who wish to consume it.

Posted: November 19th, 2011 | Author: | Filed under: benlakey.com | Tags: , , , | No Comments »

The Law of Demeter

Hello boys and girls, it’s been a while. Let’s talk about OO design.

Have you heard of the Law of Demeter? If you develop software, you should. You may actually be familiar with its concepts without actually knowing that it had a formal name. At it’s core, the Law of Demeter is the explicit capture of the intent of encapsulation. The rules are as follows.

A method FooMethod of a class Foo should only call the methods of these:

  • Foo
  • An object created by FooMethod
  • An object passed as an argument to FooMethod
  • An object reference held as an instance variable of Foo

Uncle Bob summarizes it nicely: “In other words, talk to friends, not to strangers.”

This all sounds dandy and obvious, but it’s easy to forget and slip up when dealing with complicated designs, or designs that are poorly understood.

Happy coding.

Posted: July 18th, 2011 | Author: | Filed under: benlakey.com | Tags: , , , , | 1 Comment »