The Daily Build

Icon

Software Development, version 3.0

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.

Share and Enjoy:
  • del.icio.us
  • Digg
  • Sphinn
  • Facebook
  • Mixx
  • Google Bookmarks
  • Twitter
  • FriendFeed
  • Posterous
  • email

Related posts:

  1. Who Else Wants Better Short Term Memory? In “Talent is Overrated”, Geoff Colvin at one point...
  2. If the comments are ugly, the code is ugly If the comments are ugly, the code is ugly...
  3. Insist on Automatic Tests At some point your team is going to be...
  4. Set Your zsh Prompt Since the beginning of time, all the cool kids have...
  5. 3 Easy Ways to Stick to a Coding Standard When you’re writing python, you don’t need a lot...

Category: engineering

Tagged: ,

Leave a Reply

About Me

Related Posts

Related posts:

  1. Who Else Wants Better Short Term Memory? In “Talent is Overrated”, Geoff Colvin at one point...
  2. If the comments are ugly, the code is ugly If the comments are ugly, the code is ugly...
  3. Insist on Automatic Tests At some point your team is going to be...
  4. Set Your zsh Prompt Since the beginning of time, all the cool kids have...
  5. 3 Easy Ways to Stick to a Coding Standard When you’re writing python, you don’t need a lot...