Tag Archives: javascript

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 Javascript. For example:

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.

Languages and their Operators

Did you know that in JavaScript, if you do this:

'5' + 3

You will get 53, because it coerced the 3 into a string when it needed to perform a concatenation ‘+’ operation against the string ’5′.

But if you do this:

'5' - 3

You will get 2, because it coerced the string ’5′ into a number to perform subtraction against another number.

That’s what happens when you have a weakly typed language; It attempts to do the right thing based upon the operator and operands, and you’ve got to be careful to understand whats going on.

Another oddity… In Java:

Integer foo = 1000;
Integer bar = 1000;

foo = bar; // true
foo == bar; // false

The above happens because the first two operations are numeric equality checks, while the last is a reference equality check. ‘foo’ and ‘bar’ do represent numeric values, but are not the same reference.