Five ways to create objects – part 2: Inheritance

Let me start by saying I think inheritance is somewhat overrated in JavaScript. A lot of the inheritance you are going to need is already created for you: Function, String, Number etc. all inherit Object via its prototype.

I actually wonder if more energy goes into intellectual exercises around JavaScript inheritance than into using inheritance for real time solutions. Yes, JavaScript has an excellent inheritance mechanism but lets face it all those examples with furry animals, hierarchies of wheeled vehicles and the like have little real world application in client side coding.

How often do your new objects really need to inherit from other new objects you have created? By its nature the client object modelling is essentially flat (like your monitor). If you find yourself in JavaScript creating complex java-style object models with layers of inheritance then you might want to ask yourself why. Ajax allowed us to defer to the server where we used to have to clone our business/server logic on the client. I’d argue such complex data structures are best left to the server, because they perform better, are more easily distributed across subsystems and are probably more suited to classical OOP.

With that said, JavaScript does offer a very nifty inheritance strategy – there are no classes – objects inherit from objects. Period. It’s clean and its simple.

So here goes..

Continue reading

The Case against Switch

I’ve never been fond of switch statements, whether in JavaScript or Java. They’re big and hard to follow, and of course if you forget the break keyword after each case you enter fall-through hell. (Since break statements are almost always intended it seems a pain to have to add them manually). Using objects as hash table for look-up is a simple and elegant alternative:

Example 1: Using switch is hard to read and the data is mixed with the logic

var whatToBring;
switch(weather) {
    case "Sunny":
        whatToBring = "Sunscreen and hat";
        break;
    case "Rain":
        whatToBring  ="Umbrella and boots"
        break;
    case "Cold":
        whatToBring = "Scarf and Gloves";
        break;
    default : whatToBring = "Play it by ear";
}

Example 2: Pull data into object construct. Data and logic are separated.

var whatToBring = {
    "Sunny" : "Sunscreen and hat",
    "Rain" : "Umbrella and boots",
    "Cold" : "Scarf and Gloves",
    "Default" : "Play it by ear"
}

var gear = whatToBring[weather] || whatToBring["Default"];