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!

No more coding, gone fishin’…

TL;DR; – This is a no-content post, so feel free to ignore. And I am not drunk, this time.

I haven’t blogged since ages but I have been collating my to-be blogged thoughts in Evernote. Among all those collected items, this topic was the last sequentially but I thought it to be the first to be written down. I believe it is just a natural phenomena that during our younger days, our birthdays got us thinking about parties, the gifts we would get, the celebrations, cake, trumpets, elephants, giraffes (alright I am losing here…). A part of the natural phenomenon is also that once we are around our thirties, we do get some of the above thoughts, and one more with it… I got older by a year! I mean come on, its just a friggin birthday, every one has it. But somehow recently one word popped up in my mind which took me by a bit of a surprise. Retirement.

Hah… No way I am 33 there is shit load of time, so many years to go, so many new things waiting for me somewhere. But then I think, I have not seen a single retired software developer. I do not know where to find them. I am talking about someone who started as a computer science graduate and then pursued software engineering as a profession and has been with it all his/her life. Now dont bring in some big shot in our industry who is now donating all his money, I am talking about an average developer, got it? It might be a dumb thought because our industry is far too young compared to other disciplines like architecture, medicine etc. Somehow I am able to imagine my parents retiring in their profession which is one of those matured ones, but not myself. This thing comes in my mind because for sure I do not want to see myself on stack overflow searching for an efficient way to find duplicate letters in a string in C language. That’s right, I started with C#, then did some Java, now doing Javascript, next I have a feeling its going to be C++, and if I do not get a good hold of myself then around 40 Ill be reading Kerninghan & Ritchie while my kids play super mario on my laptop (yes there will be super mario then). Seriously I am not drunk today. Some out there have retired at my age (go Google them), if I do such a thing my family would abandon me, which is cool in a way Smile.

On a serious note, what should a developer do when such thoughts start creeping his/her mind. Surely I am not worried about something that is not an issue at all. I think if we are unable to see ourselves something may be 5-10 years down the line then it is like rowing your boat without knowing where you want to go. Its fun for now, but later time will catch up with you. I am afraid to say I am rowing my boat pretty hard, learning cool new hip hop things which will get pretty old tomorrow (especially in javascript), but I do not know where I should be heading. I do not want to be coding at 40, period. But then what, move into management is one of the obvious thoughts. Meh…, may be not. There are so many monkey managers around me I hardly want to see myself as one of them. But hey dont remind me of this blog post if you see me as a manager somewhere! Doing something out of the box and something completely unrelated to software is a thought I think every software guy/gal holds somewhere in a tiny corner of their brains. I have made many friends in different countries, some want to start a dairy farm, some want to start a restaurant (I do), some want to live in a van down by the river…These are things that we developers feel are not as hard as writing code, but I know they will be much tougher to even start, maintaining it is a different game all together.

So this is where I am, I am 33 doing good coding, liked by many, hated by some (mostly wife) and thinking what the fuck I should be doing before I turn 34. I think I will be coding, what do you think!

Happy Programming!

A long precarious way…

TL;DR; = This post is about improving the way you write deep null checks in C#, i.e. a chain of If-not-null checks along the object hierarchy.

I am sure there have been times in your developer life when you saw something like this, 


class Person
{
public Address Address { get; set; }
}

public class Address
{
public State State { get; set; }
}

public class State
{
public int PinCode { get; set; }
}
...
...
var p = new Person();
...
...

if (p.Address != null && p.Address.State != null)
{
var pin = p.Address.State.PinCode;
}


Ugh.., yes you have… The point is you have to go through a lot of checks in between to reach the PinCode field. In this example there are just 2 checks for Address and State, but there could be more complicated scenarios. While talking about this, I do understand by the Law of Demeter we should not be having such deep checks in the first place. But for this blog post sake, consider this as some hairy legacy code. Moving on, there is a way you could do the same thing but in a much more readable way. What I want to do is in case of a null instance anywhere in the chain of objects, the final value should be a default decided by me, without any null reference error. Here is my attempt,




public static class Extension
{
public static TResult With<TSource,TResult>(this TSource source, Func<TSource,TResult> evaluator, TResult failureValue)
where TSource : class
where TResult : class
{
if (evaluator == null)
throw new InvalidOperationException("Boom!!!");
var res = source != null ? evaluator(source) : failureValue;
return res ?? failureValue;
}
}

public class Person
{
public Address Address { get; set; }
public static Person NullInstance
{
get
{
return new Person() { Address = Address.NullInstance };
}
}
}

public class Address
{
public State State { get; set; }
public static Address NullInstance
{
get { return new Address() { State = State.NullInstance }; }
}

}

public class State
{
public int PinCode { get; set; }
public static State NullInstance
{
get
{
return new State() { PinCode = -1 };
}
}
}

...
...

var pin = this.With(x => p, Person.NullInstance)
.With(x => x.Address, Address.NullInstance)
.With(x => x.State, State.NullInstance).PinCode;


Definitely more readable huh.