Clean Switch Blocks

There's a time and a place for switch blocks in programming.  Normally you switch on a variable, then provide a number of case blocks that provide a (hopefully succinct) chunk of code to be executed if the switch variable matches the case value.

<?php
switch($pizza) {
  case 'italian':
    $ingredients = array('ham','pepperoni','onions','peppers');
    break;
  case 'mediterranean':
    $ingredients = array('garlic','feta','tomatoes','spinach','olives');
    break;
  case 'hawaiian':
    $ingredients = array('ham','pineapple');
    break;
  default:
    // plain ol' cheese - borrrrrring
    $ingredients = array();
}
?>

Simple, right?  But there are often times when you'll find yourself building a long, kinda ugly-looking if/elseif/else block simply because you need to evaluate something more complicated than the value of a variable.

<?php
if($a && $b) {
  func1();
} else if($a && $c) {
  func2();
} else if($b && $c) {
  func3();
} else if($c) {
  func4();
} else {
  func5();
}
?>

Those happen all the time and there's nothing wrong with them.  Well, except for my contrived example.  Forgiveness, please.

But you can often improve readability by putting blocks like this into a switch statement.  The trick is to invert the placement of the switch variable and the case values.  A switch operator can take any value statement and compare it to a number of other values (cases), so it follows that we can use a static value at the top.

Try this:

<?php
switch(true) {
  case $a && $b: func1(); break;
  case $a && $c: func2(); break;
  case $b && $c: func3(); break;
  case $c:       func4(); break;
  default:       func5();
}
?>

This does the same thing as the if/elseif/else block above, but it's more compact without sacrificing readability.  But, like switch statements, there's a time and a place for them.  If you have a lot of code that needs to go in each case block, then it's probably better to put the code in functions, or failing that, in a normal if/else block.  Big bulky case statements can be tough to read, since they don't have the normal block delimiters.

Have any other useful programming idioms to save time or space?

1 Response

  1. Sebastien Duquette Says:
    March 31, 2009 at 5:50 pm -0700

    You often hear that programming is a mix of logic and art. Well you really made it a little more artistic to me today. Keep up with the good content.


Add Your Comment