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!


Write to be right

I think a lot. I mean I think beforehand about the work I might have to do the next day in office, I think about the items I need to buy for an upcoming event, I think about the repairs I need to get done in my house this month, I think about the movies I got to watch and sometimes I think why am I thinking so much! I think (shit I am doing it again), it is a good idea to plan ahead your day to optimally get things done. It is one of the strategies to be more productive in your life. Its just that it takes a toll on my head (especially the frontal area). Man so many things running at once in my head at a time that it sometimes affects my sleep too. Worst thing is (I think its a bit funny), that my wife is talking to me about something and am drawing blanks at her coz I am thinking whether to use apply or spread operator in my code Hot smile(This joke was only for the Javascript folks).

There are many books around that can help you address these issues and still be productive day in and day out. I have perused some of them but if you are like me, you cannot survive the whole material the author has to say. We are a species that like to see more of the actual stuff than just words. So just for those who want the high order bit of the big message here is, write it down! Write down friggin all the things (technical, non-technical) that come to your mind that you need to take care of in coming days. Use any note application, you could use pen and paper if you are one of those types. I use Evernote application on my iPhone. You could literally use any method that suits you to record your items. As of now I have certain categories decided that suite me, like IMPORTANT, BLOG TOPICS, OFFICIAL,  GENERAL etc. IMPORTANT includes all the items I write for actions I need to take within a day or 2. BLOG TOPICS are my ever increasing topics I need to vomit about on this blog. OFFICIAL is the list of things I intend to work in coming days at my office, this includes some items which I maintain in my TODO.txt file on my office machine. TODO.txt is just my way of keeping track of things I will be doing today after reading the mails and having discussions/meetings with the team. GENERAL are just things that do not require immediate attention, but need to be done in a months time or so. Generating this list takes few minutes of a day. The most crucial aspect of this method is to maintain it regularly and get a habit of reading this list at end of the day. If you do not do these 2 things then this method aint’t gonna work. When I get back from office, after being relaxed for some time on my couch I open up my notes and go through them to remove items I have already done and add items that I am thinking about to do soon. I am glad to say I feel a bit light headed these days and I am not missing out things that I used to forget earlier. Hope this method helps you too if you are in need.

Happy Programming!