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!



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.


Temptations of Scala…

As I continue my romance with Scala language, I decided to take up the rubber duck code from Head First Design Patterns. The code already is implemented using Strategy pattern as we know. Just check the C# code juxtaposed against the Scala code, (dont ask which one is C# code)
class Program
{
static void Main(string[] args)
{
var actualDuck = new Duck(new ActualFlyBehavior(),
new ActualQuackBehavior());
actualDuck.DoFly();
actualDuck.DoQuack();
var rubberDuck = new Duck(new NoFlyBehavior(),
new NoQuackBehavior());
rubberDuck.DoFly();
rubberDuck.DoQuack();
Console.ReadLine();
}
}

public class ActualFlyBehavior : IFly
{
public void Fly()
{
Console.WriteLine("I am actually flying!!!");
}
}

public class ActualQuackBehavior : IQuack
{
public void Quack()
{
Console.WriteLine("I am actually quacking!!!");
}
}

public class NoFlyBehavior : IFly
{
public void Fly()
{
Console.WriteLine("---");
}
}

public class NoQuackBehavior : IQuack
{
public void Quack()
{
Console.WriteLine("---");
}
}

public class Duck
{
private readonly IFly fly;
private readonly IQuack quack;

public Duck(IFly fly, IQuack quack)
{
this.fly = fly;
this.quack = quack;
}

public void DoFly()
{
fly.Fly();
}

public void DoQuack()
{
quack.Quack();
}
}

public interface IFly
{
void Fly();
}

public interface IQuack
{
void Quack();
}
object Starter extends App
{
println("Hello World!!!")
val actualDuck = new ActualDuck
actualDuck.doFly()
actualDuck.doQuack()
val rubberDuck = new RubberDuck
rubberDuck.doFly()
rubberDuck.doQuack()
}

abstract class Duck
{
def doFly()
def doQuack()
}


class ActualDuck extends Duck with Fly with Quack
{

}

class RubberDuck extends Duck
{
def doFly() {println("---")}
def doQuack() {println("---")}
}

trait Fly
{
def doFly(){println("I am actually flying!!!")}
}

trait Quack
{
def doQuack(){println("I am actually quacking!!!")}
}
 
 
 
 
 

Pocket it!

Ok so I might be a little late to the party, but nonetheless I am in the party now. Since I do follow many blogs and in search of new interesting blogs all the time, I always have this situation wherein I do find something really intriguing to read but have to save it for later. The things that interest me are coding blogs for Java, C#, Scala (I mentioned them in the increasing order of coolness), lifehacker like blogs, Agile, Daily WTF of course and the list goes on. I needed something that I can use on any of my devices, iPhone, iPad, Mac, my Dell laptop. I needed something that could do the job in at the most one click. That is the best you could do really (cant think of any quicker way really). I did hear quite a bit about EverNote and it is an excellent tool. Although somehow it is not like a one click solution I was looking for.

And then this Pocket shows up. The first thing I looked was the list of devices supported, satisfied there. The second thing was how it is used. It really has a one click solution if you are already using a supported feed reader. I use Feedly (which is an excellent replacement for Google Reader). So all you do is while you have your blog post open, just click the “Pocket” icon button at the top, thats it. End of Story! May be not. I use Chrome as my browser for reading blogs when I am on a laptop or desktop. Its got a Chrome plugin that behaves pretty much the same One-Click way I just mentioned. If this explanation was too complicated for you, they even have a short video on how to use it, go check it out. This is really End of Story.

Happy Pocketing!


A polyglot “C#”er

My professional career until now (spans barely 8 years), has been mostly “C#”ish. I liked the language when I started working with it, and really enjoyed staying within the Visual Studio editor. While I was working earlier in my career, I did find interest in reading several blogs about being a better programmer as a whole. The word “polyglot” reverberated in many such well thought blogs. I did understand at the point that having exposure to many languages will equip me better in my work. But here is my honest take on it now that I have spent some reasonably sizable amount of time with a language.

You got to know a particular language well first. For me it is undoubtedly C# as it stands. Once you have that under your sleeves, when you start exploring other languages you learn them in a different way than you would have learnt if you had not mastered a language. It becomes just involuntary that you start comparing features of this new language to the language of your forte. And with this the benefits are two-fold, you learn the new language faster, and you find better ways of solving problems in your mastered language. I think the second point is really exciting for me as I venture on learning new languages and paradigms. For some limited time now, I have worked on Java professionally. I have taken a stab at Scala and Haskell during my personal time although it is not usual to find these 2 languages easily in mainstream application development. The best way to learn languages is to solve some really common problems in computer science. I like the Producer-Consumer problem as it highlights usages of collections and threads which form the biggest chunk of the stuff we use. Below are C# snippet juxtaposed to Java snippet. Spot 6 differences to win a free trip to Goa Winking smile.





public class PCQueueCharp
{
private Queue queue = new Queue();
private static readonly object SyncLock = new object();

public PCQueue(int capacity)
{
Capacity = capacity;
}

public int Capacity { get; private set; }

public void AddTask(ITask task)
{
lock(SyncLock)
{
if (queue.Count == Capacity)
Monitor.Wait(SyncLock);
queue.Enqueue(task);
Monitor.Pulse(SyncLock);
}
}

public ITask RemoveTask()
{
lock(SyncLock)
{
if (queue.Count == 0)
Monitor.Wait(SyncLock);
var task = queue.Dequeue();
Monitor.Pulse(SyncLock);
return task;
}
}
}


public class PCQueueJava
{
private int capacity;
private final Queue queue;
private static final Object SyncLock = new Object();

public PCQueue(int capacity)
{
this.capacity = capacity;
queue = new ArrayDeque(capacity);
}

public void AddTask(ITask task) throws InterruptedException
{
synchronized (SyncLock)
{
if(queue.size() == capacity)
SyncLock.wait();

queue.add(task);
SyncLock.notify();
}
}
public ITask RemoveTask() throws InterruptedException
{
synchronized (SyncLock)
{
if(queue.size() == 0)
SyncLock.wait();
ITask task = queue.remove();
SyncLock.notify();
return task;
}
}
}



And here is a beginners implementation in Scala



class PCQueue(capacity:Int)
{
val queue = new mutable.Queue[ITask]()
val syncObject = new AnyRef

def addTask(task : ITask) : Unit =
{
synchronized
{
if(queue.length == capacity)
wait()

queue += task
notify()
}
}

def removeTask() : ITask =
{
var task : ITask = null
synchronized
{
if(queue.length == 0)
wait()

task = queue.dequeue()
notify()
}
return task
}
}

The idea is to improve this class in Scala to make it more “Scala”ble in a later post.

A legend from my city

 

a

When I started my blog I was quite sure I was not going to write only about technology. It was in general about my experiences as I move along in my career and the things I have seen and learned on the way. There are and will be certain events that will be embossed in my mind forever and will be cherished for life time. Somehow, all the days I spent with my friends and family watching India play cricket all these years, finally crystallized into one final day when Sachin started his farewell speech at Wankhede stadium, Mumbai. I remember my mom watching some family serials where she shed tears for the hapless women they showcase. I’ve never seen my dad crying. But while Sachin was talking, I could see both of them wiping their eyes, and I felt moist under my eyes too. I was a bit choked up while writing this post. There are a plethora of photos and videos and talk shows picking up all kinds of analysis on what Sachin said on his last day. The most important thing for me is, Sachin to me was just another enthusiastic cricketing boy in Mumbai playing at Shardashram. My cousin also did that, left his school near his house and admitted himself to the temple of cricket. Sachin must have taken the bus like me in the city at some point. His house is about an hour drive from mine, but he just feels like a neighbour to me. And today India has a stamp with his face on it. For me he is a symbol of dedication, hardwork, supreme passion and honesty. I am being a bit selfish here when I said this legend is from my city as I am proud of that fact. But he belongs to the whole nation.

There are certain people I have in mind about whom I shall teach my kids when the time is right for them. Sachin Tendulkar fits right among them for me. Whether my kids decide to be sportsmen or sportswomen, he is a book to be read by them.

Salute!


The case of evil brackets

It was just another day at work, setting up Tibco EMS with Weblogic server on my 32 Windows XP machine. Umm, you know what, that is not what I do most of the time. But lets keep it that way for this blog post. I had Tibco EMS installed on my machine, and wanted to put this path C:\Program Files\Tibco\ems\tibjms.jar in my ClassPath environment variable. I went ahead, and started the Weblogic server instance and it worked like a charm. The twist came when I had to set up another instance of Weblogic on another machine. But wait, that machine was a 64 bit machine. Tadaaaa!!(an evil music). Ok that was too much.

Anyways, I had Tibco ems installed there at C:\Program Files (x86)\Tibco\ems. (Ah, hence the post title Smile). I went about with the same steps mentioned above, and got a nasty ClassNotFound error while starting up Weblogic server instance. I have limited knowledge with Java, but this was surely some kind of class resolution problem. Hmm, I sure did put the path to the tibjms.jar file correctly. I had a bad feeling with those brackets, but just to make sure, I headed to StackOverflow, (yaya, I went to Google and then StackOverflow, pff…). As expected, there were many poor souls like myself who faced similar problem. The problem was certainly with the parenthesis present in the environment variable. The solution I applied was to not edit the ClassPath variable directly. But rather,  open the startweblogic.cmd file and append the C:\Program Files (x86)\Tibco\ems\tibjms.jar path to the      %CLASSPATH% variable in the cmd file. And the started the server, Skadooosh!!! But you know what, it really gets me thinking here, the folder “Program Files (x86)” is a folder name that Windows decided I believe, ClassPath usage is in the Java world. Did Windows do this with a purpose to torture folks trying to do Java on Windows Angry smile.


Fusion Log Viewer to the rescue

OB-DF012_captpl_E_20090225180300

I know this is not the kind of image you have right now in your mind after reading the post title. Seems like the Chicken Fight in Family Guy that has got nothing to do with the on going plot Smile. But let me belabour! The other day one of my colleagues came at my desk with a possible logging issue in his application. The application was logging just fine until the day before. The application was using log4net for logging its stuff. There were no logs being generated whatsoever. Inarguably the place to look for was anything goofy in the configurations. Nope, things were all ok there. The folders used for logging had proper accessibility for his username. I asked him whether there was any recent change done like an upgrade that might have anything to do with this. Bingo, there was a recent patch release done to fix few important bugs due to which the version numbers of the assemblies were upgraded.

Equipped with that piece of information, and a boat load of anxiety I popped opened the Fusion Log Viewer (fuslogvw.exe) in Visual Studio command prompt. I enabled the logging for binding failures and started the application. Skadooosh!!!! I saw one assembly bind failure log shining right in my face. My colleague looked at it, and gave a smile that a developer gives when he “gets it”. It happened so that the assembly redirect configuration in app.config for one of the assemblies was incorrectly put and hence this wrong behaviour. I don’t know about you, but Fusion Log Viewer did save our day, and it reminded me of one of my childhood favourite characters, Captain Planet (for those who have no clue what is the flying guy all about).


What a Moqery…

Every new technology that comes into a developer’s hand goes through a so called “honeymoon period”. I’ve been hooked onto Moq these days. I am quite sure down the line, few years pass by and I shall be using something more "usable” than Moq and would consider that as my best mocking tool. But that is just another page in a developer’.

Back to the meat of this blog, the other day I was mocking certain classes for writing some behavioural tests. There was a reason to mock certain properties of a class. For Moq to mock the property it has to be marked as virtual. Ideally, I would have it part of an interface that can be mocked with Moq. But that is a different topic all together. To put forward my point, look at the below code snippet of a pretty dumb method “DeReplace”. All it does is for the string stored in BarProperty, it replaces ‘a’ with ‘@’.

private string bar;
public virtual string BarProperty { get { return bar; }set { bar = value; } }

public string DoReplace()
{
if(String.IsNullOrEmpty(bar))
{
throw new InvalidOperationException("The bar string cannot be null or empty.");
}
return bar.Replace('a', '@');
}


One heck of a useful method eh! This is a test for the above method using Moq,



[TestMethod]
public void TestBarStuff()
{
var mockBar = new Moq.Mock();
mockBar.SetupGet(x => x.BarProperty).Returns("skadoosh!!!");
var result = mockBar.Object.DoReplace();
Assert.AreEqual("sk@doosh!!!", result);
}


Did it work. Of course not. It resulted in the InvalidOperationException and the assertion failed. Why? We did setup the BarProperty correctly with Moq, but what are we using in our original method? We are using bar string. This does bring back the discussion whether to use properties for local usages or just use local member variables. I shall leave that discussion for StackOverflow, but one thing is pretty clear. If you intend to mock properties for a class, you better use them in your methods. Below is the changed class to make the test work,



private string bar;
public virtual string BarProperty { get { return bar; }private set { bar = value; } }

public string DoReplace()
{
if(String.IsNullOrEmpty(BarProperty))
{
throw new InvalidOperationException("The bar string cannot be null or empty.");
}
return BarProperty.Replace('a', '@');
}

Ahh that green color, sweet.

Happy “Moq”ing.


Some “Moq”ing

I have become a big fan of Moq since I started using it. The reason I like it so much is its ease of use. I have not bothered to learn Rhino Mocks or NMock for that matter coz since I have started using it, its the 3rd team I have joined for a project where they have choosen Moq over all others.

Right, back to work. Did you ever have a requirement where you had to mock some methods of a class and leave out certain methods as is? Consider that following utterly useless classes,

public class Foo
{
public string CallMe()
{
var result = DoSomethingImportant();
return result.ToString();
}
public virtual int DoSomethingImportant()
{
return 10000;
}
}

public class Bar : Foo
{
}

Ya they are pretty dumb I know. The point is this, say you would like to mock the Bar class and test out its CallMe method. This is how it might look,

[TestMethod]
public void TestBarStuff()
{
var mockBar = new Moq.Mock();
var result = mockBar.Object.CallMe();
Assert.AreEqual("10000", result);
}

You run this test and you meet this error,

image


The problem here is, you sure have a virtual method in Foo, but there is no overridden implementation provided in Bar. Moq underneath derives from the target class (in this case Bar) and injects its setup implementations for the virtual members as provided. Although, if you intend to leave a method in the base class (Foo) as is, you need to tell Moq to do so. Common it can’t be that smart! To do this, use the “CallBase” property on the mock object. This does exactly what it says and calls the base virtual implementation in case a setup is not matched. Below is the working test for the same,

[TestMethod]
public void TestBarStuff()
{
var mockBar = new Moq.Mock();
mockBar.CallBase = true;
var result = mockBar.Object.CallMe();
Assert.AreEqual("10000", result);
}

Now run the test again. I just love when I see that green color, dont you!

Happy Moqing!


The Previous Job

I have actually stopped apologizing for not blogging more often. Anyways, my bad Sad smile

This time I just wanted to share some of the emotional experience related to our work. The reason being, its my… I think 5th switch to a new job since I got into this profession of software development. (Ya, I know I am too unstable, moving on).These companies spanned in the Americas, Asia and India. And every time I move on to my next gig, I get this feeling which I wanted to share.

So, a small flashback. I am serving notice period in a company that I am about to leave. This period is aptly called the “Honeymoon Period”. I barely give a crocodile’s ass about the quarterly results, eschew the blah blahs of the manager, I am already feeling so wonderful, everything is suddenly so perfect. The rush hour in the train feels pretty cosy. To add a cherry to the cake, I am leaving the country and looking forward to move back to my home town to work for a “better” company (snickering). Days fly, notice period is over, the good byes are done and here I am in my home town, looking at my laptop thinking about my previous job. What comes to my mind first it the place where I lived. I look at building I stayed for so long using Google StreetView. All the people I interacted with more throughout the day come one after the other flashing in my mind. Certain memorable events, good and bad, consciously come and go in my head. And then I say it aloud in mind, have I taken the right decision? Hmm, deja vu I guess. Smile

One slight point I want to make here is, no matter how much you hated your job, what matters is the relations you have built up. The culture of the new place, the nuances of human nature you experienced here, and most important the friends you made. These things will stick with you all your life. You might have had grudges with one or few of your team members, and that might be reasonable too. But the relations you make, friendships are way way above the work you did. So the last thing you should do is to blurt out all the anger on your manager’s/colleague’s face and walk out. The world is too small as I see it, especially in our profession.

So, it happened to me this time too, I am shedding away that thought for now and looking forward for a next Deja Vu experience Winking smile.


Why don’t you use Mocks?

In a developer’s life, he might work on numerous projects. Some are truly greenfield, some are not so much and some are absolutely not. I would bet that most projects we developers end up have already got quite a bit of code base already in place. Doing a proper Test Driven Development (TDD) means writing your tests before your code and then repeat process improving the code base test by test. Well if you see in case of projects that are fairly matured or in their maintenance stage, not all parts of the project can be pure TDD anymore. One would get an opportunity when a new feature is requested or a requirement changes to get his hands on implementing TDD in a restricted kind of way.

With that fact out of the way, the other day one of my colleagues had a hallway talk with me “You know we have been really slacking on our unit tests. For our new feature XYZ, we should follow proper unit testing cycles”. Umm… sure. “Ah and yes, please use Mocks ok”. WTF! There is a general belief among certain set of developers/leads that if they see unit tests with usage of some Mocking Framework, the tests must be well written and are strong. Experienced TDD practitioners must already be spitting bullshits all over this blog post, but really I have heard and seen this a lot. Most of the times, I have seen tests where the intention was to actually have some dummy implementation of some class as a placeholder but still went ahead to use a mocking framework. Now there is nothing wrong here, one can use a mocking framework to create a “Stub” but then that is not the main reason why mocking frameworks exist. The high order bit when it comes to mocks is “Behaviour Testing”. Testing that involves checking the interaction between objects in your component is best done with a mocking framework. If a default implementation is your sole intention, then as long as your code is well written with inversion of control pattern, a dependency injection container can do the job. See this,

public void TestIsThisMockingAtAtll()
{
var mock = new Mock();
var d = new DataAccess(mock.Object);
Assert.AreEqual(5, d.GetDataItems().Count());
}


I would say we have not done any behavioural testing here. All we have done here is create a stub object and used to do some state testing on the DataAccess class. If you have such tests and you claim you are using mocks heavily in your tests, you are creating a mockery of yourself Angry smile.

Happy Mocking!


The rewriting trap…

I cannot count the number of times I have heard this phrase by a fellow developer “The component XYZ is an absolutely stinkin pile of %&^&*#, we need to rewrite the whole thing”. Actually I remember saying it once or twice myself. Probably in very rare cases this might hold true, but in most cases rewriting the whole thing would end being the wrong path to choose. It reminds me of the problem Netscape folks had faced a long long time ago…

When a component is developed, it has undergone many cycles of iterations, some demonstrations with clients. And needless to say, thousands of bugs that were reported over the period. (I say thousands because my current project JIRA count has crossed it way long ago.) So we have this old guy settled in its position for a long time and has grown many “things” around it so it looks hideous. But there is another word to explain this, matured! Rewriting this whole thing might make the code cleaner (which is a very subjective term anyways), but to get the component where it is not with clean code, that most probably would not be a trivial task. And not worth it too. As a proud member of the developer species, I do feel the yucky feeling when I see bad code smells all over the code base. But just dumping the whole thing and rewriting from scratch is almost never a wise option.

The only way to move in the right direction is Refactor. Before which, have strong unit tests for the component so that changing things around is a safe game.


Driving with Tests

I admit I am not a strict TDD developer. I write my logic first, and then move on to writing tests wherever I feel its applicable. It works for (at least until now), and looks right to me. This year I have put down an objective for myself to be a bit more strict in this area. I would want to start any feature implementation by writing its tests first and then get the code done, thus driving with tests. As a start, I did a small piece of functionality with this approach, and, I actually enjoyed it. I mean I enjoyed it so much that I was supposed to leave office early to get somewhere, I actually postponed it to complete my TDD approach. Sweet!(Umm that’s geeky, I know I know…) I had heard several experts saying that once you get onto the wagon of TDD, it would be the feel the most appropriate thing to do and would be hard to get off it.

I would suggest folks like me out there to give it a shot, make a task in your Outlook (or Lotus Notes, good bless you in that case!) to implement at least one teeny tiny feature with TDD approach. I think you would appreciate it. And if not, well… no one is stopping you from the Gung-Ho style Winking smile.

Happy Programming!