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!