4 ms·
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 readab
by MatthewPhillips 13y ago
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.
- mistercow 13y ago>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.
- rco8786 13y agoAlso, 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.
- eckzow 13y agoThe 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 http://en.wikipedia.org/wiki/Open/closed_principle