Data vs Code

I'll take an array over a giant switch-case statement any day.

  1. The array definition will be more compact and easier to see all at once.
  2. Defining actions in an array enforces uniformity.
  3. You can put checks in the code to automatically verify that the array definition is complete. (I.e. verify it contains a definition for every item it should have.) Yes, some tools can do this for certain types of switch statements. Using an array-based check is more portable and more foolproof.

If you have a switch statement of mostly cut and paste cases, you can probably convert it to an array very easily, and then rewrite the switch statement to look up the value in the array and do whatever thing is supposed to be done, either via function pointers or by using an associated value from the array.

I did this on a horrible switch statement once. Dozens of cases, 80% were nearly identical but the few that weren't were awful to untangle. Once I pulled the case bodies into separate functions, put function pointers into a table, and replaced the switch body with a lookup loop it was much cleaner. The code for the odd cases was eventually pushed out (it was a symptom of bad design). The whole exercise enabled another round of changes that allowed the functions for the case bodies to be collapsed back into the table -- we ended up removing an entire unnecessary layer of indirection and made the design much easier to grok.

Posted on 2010-02-05 by brian in engineering .
Comments on this post are closed. If you have something to share, please send me email.