Namespaces in Javascsript

I am a recent convert from the good land of OOP languages (class oriented languages to be technically correct), to the bizarre land of Javascript (truly object oriented). Doing Javascript for fun is one thing but doing it at a large scale professionally requires certain practices that have been built over the years in enterprise world. One such practice is organizing your classess (function objects), into logical partitions or rather namespaces.

Like quite a few things that a regular C#/Java guy would find amiss in Javascript, namespaces are one such thing. As I work more with Javascript, one thing that hits is there are not many bits and pieces to learn really. In C#/Java you got to learn many aspects of the language itself, but in Javascript it just functions and you got to build everything from it. Now lets consider how we might create a namespace to organize our function objects into each of them correctly. Say we need to generate namespaces like,

  • Hogwarts,
  • Hogwarts.Griffindor
  • Hogworts.Griffindor.Muggles
  • Hogworts.Griffindor.Wizards

Below code snippet just does that,

var Hogwarts = Hogwarts || {};
Hogwarts.Griffindors = Hogwarts.Griffindors || {};
Hogwarts.Griffindors.Muggles = Hogwarts.Griffindors.Muggles || {};
Hogwarts.Griffindors.Wizards = Hogwarts.Griffindors.Wizards || {};
Hogwarts.Griffindors.Wizards.Harry = function(){
    this.name = 'Harry Potter';
};
Hogwarts.Griffindors.Wizards.Ron = function(){
    this.name = 'Ronald Weasley';
};
Hogwarts.Griffindors.Muggles.Hermione = function(){
    this.name = 'Hermione Granger';
};

This creates a Hogwarts object at window level and organizes all other objects under it. This works just fine but a bit verbose and repetitive I bet. A cleaner way could be to generate these objects on the fly as long as you pass the namespace string correctly. Here is a method that generates Harry, Ron and Hermoine in their respective namespaces,

var namespace = function (ns) {
    var parts = ns.split('.');
    if (!parts || parts.length === 0) {
        return;
    }
    window[parts[0]] = window[parts[0]] || {};
    var current = window[parts[0]];
    var startIndex = 1;
    for (var i = startIndex; i < parts.length; i++) {
        var part = parts[i];
        if (!current[part]) {
            current[part] = {};
        }
        current = current[part];
    }
    return current;
};

And now we just create the objects we want.

var Wizards = namespace('Hogwarts.Griffindors.Wizards');
Wizards.Harry = function(){
    this.name = 'Harry Potter';
};
Wizards.Ron = function(){
    this.name = 'Ronald Weasley';
};
var Muggles = namespace('Hogwarts.Griffindors.Muggles');
Muggles.Hermione = function(){
    this.name = 'Hermione Granger';
};

If you think about how .NET or Java deserialization works, as long as the assembly being loaded matches the type we are deserializing, we get an instance of the type. We do not have to do anything speacial. But of course in Javascript, there is no type! What if we want to create an object on the fly by just knowing its “full type name” like Hogwarts.Griffindors.Wizards.Harry. It need not be very difficult since we already have a method that can generate namespaces right. We can have a separate method that is responsible for just this,

var create = function(fullNameSpace, args){

    var parts = fullNameSpace.split('.');
    if(!parts || parts.length === 0){
        return;
    }
    window[parts[0]] = window[parts[0]] || {};
    var current = window[parts[0]];
    var startIndex = 1;
    for(var i=startIndex;i < parts.length; i++){
        var part = parts[i];
        if(!current[part]){
            return;
        }
        current = current[part];
    }
    return new current(args);

};

And now we happily create our characters by passing their “full type name”,

var harryInstance = create('Hogwarts.Griffindors.Wizards.Harry');
console.log(harryInstance.name);
var ronInstance = create('Hogwarts.Griffindors.Wizards.Ron');
console.log(ronInstance.name);
var hermioneInstance = create('Hogwarts.Griffindors.Muggles.Hermione');
console.log(hermioneInstance.name);

Javascript deserialization in the works baby!!!

Happy Typing

Everyone needs an identity

Everyone needs an identity, that is how we identity them. Well, some need more than one…

identity_2002_20_thumb_thumb

The above still is from the movie Identity (the movie and this blog post title.. get it Secret telling smile). Well that sucked! Anways, its among my favorite movies. It is such a common thing that any one just probably just takes it for granted. But let me tell you, when 2 different “things” do not have their individual identites, well they are not any different to the naked, eye are they? Enough theatretical stuff,  here is a simple code snippet in C#:

public class Person
{
    public string Name{get;set;}
}

var p1 = new Person({Name = 'Frank Underwood'});
var p2 = new Person({Name = 'Frank Underwood'});

Now I understand the value equality vs identity equality case here, but is there any “identifier” I can use during debugging to let me know if I am dealing with p1 or p2? In C#, all objects are gifted with a method called “GetHashCode()”. This method returns a unique value for each object across all classes in your application. This number is the identifier of an object that shouts his identity, and it is mighty useful during debugging when you have bunch of objects flying around in callbacks and event handlers. It would be nice to have something like this in Javascript where things are already so “simple”. (Really Javascript is so simple and has so much less to learn, but after working with it for some time makes us realize that is the only thing that is simple.) So a similar snippet in Javascript:

var Person = function(){
    this.name = null;
};

var p1 = new Person();
p1.name = 'Frank Underwood';
var p2 = new Person();
p2.name = 'Frank Underwood';

function whoAreYou(person){
    // How do we know if here we have a p1 or p2???
}

Recently while working on a project I had issues where I was using an event library (EventEmitter of node precisely). I had a constructor function Subject that was acting as an event source. There was another constructor function Observer, that listened to those events. The scene was to have a single subject and a single observer specific to it. When I had multiple of these objects interacting with each other, shit started happening when multiple instance of Observer were listening to a single Subject. When there Javascript and shit close to one another in a paragraph more often that not its got to do with the “this” pointer. What helped me come to that conclusion was a way to identify an instance of Subject I am debugging is indeed the one I intend to be. This line of code did the trick for me:

var Person = function(){
    this.name = null;
    this.hashCode = Math.random(); // Identity!
};

Now when I debug, I tracked the objects I needed with this unique hashCode number. Sure those numbers are floats and are hard to remember but they get the job done as I see it.

That ‘Aha!’ moment with Unit Testing

I have been reading about unit testing all around me, that its good, its essential, it improves code quality, solidness etc. Well there was no denying really, in fact I was writing unit tests when working mostly with C#. But somehow it wasn’t very organic to my style of development. I mean, it wasn’t one of those involuntary tasks that I do when I am about to start writing code for some feature.

It is a tendency for a developer to first formulate the plan of action in his or her head. Then start executing by writing code. Sometimes I do use a rubber duck to talk through my design steps, sometimes good ol pen and paper works. And then create classes, functions, then refactor, and refactor again … But unit tests I admit, generally followed writing the actual logic. May be that is a crime for purists, but not me. Until I started working on JavaScript. There is a mass migration of UI developers towards JavaScript.

migration

Unless you have been living under a rock, it should be fairly obvious that most of the new projects will have their UI work sketched out in JavaScript, whether you like it or not. Search for it and you should find boat load of material on the good, bad and the ugly (mostly ugly) workings of JavaScript. But one good side effect of such dynamic nature of language is the supreme necessity of tests! I almost feel ominous to use any library that is not provided with strong test cases. The reason being, JavaScript runtime and the whole Web development experience is so forgiving that identifying any issues is delayed until you actually see the error happening. No compilation phase says it all. I admit tools like JSHint, ESLint etc make like easier, but fundamentally it is the developer who has to understand the underpinnings of the language to make it work as he or she intends. And once you do get the language, to make new team members understand whats going in, unit tests go a long way.  I almost feel saint-like when I advocate tests in my team,

god

Writing tests is one part of it, if you do not do even one of these steps you dont bother writing them in the first place:

  • Keep them fresh and updated
  • Execute them as part of daily build process and do not generate output until all tests are passed
  • A step further, you can also execute them as you write code. (This feels goood!)

So now, when its time for writing a new feature/module in JavaScript here are the steps I follow:

  • Ensure jasmine, karma and gulp is installed. Search for these terms and you should get lots of help for how to setup your development environment with these tools.
  • Turn on the autowatch in karma.conf.js so that as you change code or test files, all tests are executed and the feedback loop is instantly completed.
  • Setup continuous integration to run gulp steps so that on each check in by any team member, these tests are executed on the build server.
  • Oh yes, and now you can write code.

Happy Testing!

Go Func’ yourselves

Hah, that’s a catchy title eh… Ok, going right to the topic of this post. Every now and then we come across a requirement to have something like an observer pattern wherein, multiple listeners (observers), want to know about certain event happening on a particular subject. It is a well practised pattern in .NET, but it can be implemented just as easily in Javascript. Although the functional nature of Javascript there are essentially 2 fundamentally different ways to get a observer pattern implemented.

  • The classical way like in .NET, have a Subject that maintains a list of Observer objects. A Subject can add/remove Observers. Any event happening on Subject is notified to each Observer instance.
  • A func’y way where a Subject holds a bunch of callbacks thats it. Any event happening, and the Subject just executes the callbacks.
Each method has its own pros-cons and the approach really depends on the case at hand. The below snippet shows the first classical approach,
var Subject = function(){
this.observers = {};
Subject.prototype.addObserver = function(observer){
if(this.observers.hasOwnProperty(observer.id)){
return;
}
this.observers[observer.id] = observer;
};
Subject.prototype.removeObserver = function(observer){
delete this.observers[observer.id];
};
Subject.prototype.start = function(){
setTimeout(function(){
_.each(this.observers, function(x){x.execute()});
}.bind(this), 3000);
};
};

var Observer = function(id){
this.id = id;
Observer.prototype.execute = function(){
console.log('Executing observer %s', this.id);
};
};

var o1 = new Observer('O1');
var o2 = new Observer('O2');
var s = new Subject();
s.addObserver(o1);
s.addObserver(o2);
s.start(); // Prints 'Executing observer...' twice once for each observer.
setTimeout(function(){
s.removeObserver(o2);
s.start(); // Prints 'Executing observer...' only once.
}, 5000);

In this approach, we need instances of Observer objects even though the only thing that matters truly is the execute method on them. But with this approach, are able to maintain observer instances with their ids and clean them up as required. Sometimes it is important to not have an observer receive an event multiple times if it was fired only once. Here I have used a unique Observer id to address that issue.

Now, here is the more functional approach,
var Subject = function(){

_.extend(this, new EventEmitter());
Subject.prototype.addObserver = function(callback){
this.on('Execute', callback);
};
Subject.prototype.removeObserver = function(callback){
this.removeListener('Execute', callback);
};
Subject.prototype.start = function(){
setTimeout(function(){
this.emit('Execute');
}.bind(this), 3000);
};
};

function callback1(){
console.log('Received on callback1');
}

function callback2(e){
console.log('Received on callback2');
}

var s = new Subject();
s.addObserver(callback1);
s.addObserver(callback2);
s.start();
setTimeout(function(){
s.removeObserver(callback2);
s.start();
}, 5000);

Here, we do not need a Observer function object at all. All we register is our required callback method. It looks nice and clean and functional way to solve the problem at hand. We do need a way to collect multiple callbacks somewhere, I am using the EventEmitter (node.js module), for the job. Basically it maintains a list of callbacks for a particular event name that will be fired by the Subject. You could do this by implementing your own Event Handler mechanism. Regardless how you do, the problem that would remain is unregistering callbacks. Due to the nature adding/removing listeners in Javascript, you need to pass the exact same callback function for removing, that was passed while adding. A pointer to that function would not work too. So you see, the client code has to somehow maintain these callback functions so that it can pass them to the Subject when the client needs to remove a particular callback. This might be a cumbersome thing to do in certain cases. Barring this problem, I think this method might look attractive to most.

Happy Programming!

Saving private variable

TL;DR – This post is about implementing private variables in Javascript. I could have named this post accordingly but what’s the fun in that!

Implementing something as simple as private variables is a topic of discussions across the Javascript community. The reason is the “open” nature of Javascript wherein those typical OOPS fundamentals of encapsulation, information hiding are not natively taken into consideration. Recent converts of Javascript (like me) somehow cannot shed off the protective cover of OOPS fundamentals and hence try to twist and mould a language to fit into those well learnt dies. Javascript purists seem to disagree with such approach and embrace the language and change the programming style with it. I do agree with it, but I think there are times when there are valid reasons for classical style of inheritance, private variables, abstractions in a language which does not have a concept of class. One such case is to have private variables in Javascript. It is such a common requirement to hide those sensitive little secrets of a “class” from the ruthless outside world. There are several ways to achieve this in Javascript and you can just find them easily on the internet. Here is a way I have been recently implementing private variables using WeakMap (part of ES6 standard). I always feel the need for a function similar to GetHashCode() that we have readily available in .NET. Sometimes when “this” pointers fucks us and I have no clue which instance I am looking at, a unique id given to each instance of a “class” can be life saver. But we do not want people to change that hash value for an instance once assigned so lets keep it private.

var globalObj = globalObj || {};
(function () {
'use strict';

var privateParts = new WeakMap();

globalObj.MyObject = function(id){

this.publicStuff = 'You can see me.'; //public

var privatePart = (function(instance){

var obj = instance;
var hashCode = Math.random(); // private

function getHashCode(){
return hashCode;
}

return{
getHashCode : getHashCode
};

}(this));

privateParts.set(this, privatePart); // This would bind 'this' object with the privatePart.

globalObj.MyObject.prototype.getHashCode = function(){

return privateParts.get(this).getHashCode();

};
};
})();

var obj1 = new globalObj.MyObject('MyObject1');
var obj2 = new globalObj.MyObject('MyObject2');
var h1 = obj1.getHashCode();
var h2 = obj2.getHashCode();
console.log(h1);
console.log(h2);

Happy Programming!