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.

Abhang Rane