Wednesday, February 10, 2010

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)


Fortunately JavaScript offers the simplicity and elegance of Object literals as an 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. Logic becomes clean

var gear = {
    "Sunny" : "Sunscreen and hat",
    "Rain" : "Umbrella and boots",
    "Cold" : "Scarf and Gloves",
    "Default" : "Play it by ear"
}
var whatToBring =
    gear[weather] ? gear[weather] : gear["Default"];

2 comments:

  1. In the interest of pure parallelism, shouldn't "testCase" in Example 1 be changed to "weather"? Then it's clear that Example 2 is not introducing a new "weather" variable that wasn't needed in Example 1.

    ReplyDelete