Friday, November 19, 2010

JavaScript: Selection by Mapping

Very often we find ourselves branching in our code, and the most obvious way to do this is in an imperative style with if statements.
if (x === "case 1") { fn1(a, b); }
else if (x === 3) { fn2(a, b); }
else if (x === someObj) { fn3(a, b); }

That type of code gets tricky to read. There's lots of noise and repetition in the if and else statements, in the argument list on the function calls, and in the (x === ...) in the conditions. All that repetition can lead to errors. It's trickier to see what different about each case. There's also the opportunity to sneak in complexity increasing special cases.

The key to simplifying this is recognising that two things are happening: mapping of a condition to a function, and invocation of the function. We can separate those two things so the mapping of condition to function looks like this:
cond["case 1"] = fn1;
cond[3] = fn2;
cond[someObj] = fn3;

And the invocation looks like this:
cond[x](a, b);

In practice you'll be able to give a good name to cond that can help document what's going on as well.

However, variable arguments can be tricky, but we'll look at that in a later example.

No comments:

Post a Comment