News for hackers. Stuff that matters.
Re:Using Dispatch Tables to Avoid Conditionals in JavaScript by MatthewPhillips on Monday May 13, 2013 @09:38AM (#5698541)
While this can be a useful construct when you are doing meta-programming, this particular example is horrible. It's not much more readable (would be less readable in an 80x24 terminal window), and now you have an extra object sitting in memory for the lifetime of your application. If you only have a handful of options, just use switch.
Re:Using Dispatch Tables to Avoid Conditionals in JavaScript by mistercow on Monday May 13, 2013 @10:17AM (#5698765)
>and now you have an extra object sitting in memory for the lifetime of your application

Worrying about that would be the epitome of premature optimization.

Re:Using Dispatch Tables to Avoid Conditionals in JavaScript by rco8786 on Monday May 13, 2013 @10:22AM (#5698796)
Also, there is still a switch needed in the MovePlayer function.

So all that extra code only serves to eliminate 2 options from the original switch.

I do like the approach in some cases, I just think that the example given probably wasn't the best choice.

Re:Using Dispatch Tables to Avoid Conditionals in JavaScript by eckzow on Monday May 13, 2013 @12:20PM (#5699554)
The example definitely leaves a bit to be desired.

One great story for why this way might be better is that with a small tweak (to allow dynamic [de]registration of command functions) it is much more open to extension.

To continue using the somewhat creaky "text game" example, if possessing certain items or being in a particular room affects the available command set, this can be easily included: without a magic feather, "fly" returns "You don't know how to do that" but when you pick up said feather a new action is registered, and now "fly" works properly.

Now, I'm not sure I'd implement this particular game that way, but such an interface tends to be useful for building plugin systems, etc.

It's mainly for this reason that large switch statements, particularly those not doing "math" of some sort, tend to be a code smell.[1]

[1] http://en.wikipedia.org/wiki/Open/closed_principle