Tue
11
Jan '05
Switch is not a code-smell per se
by Frank Spychalski filed under articles, comments

If you find this useful, you might like my other articles, too.

Sonja talks a little bit about wether a switch statement is a code smell or not but seems to miss the point. I think you should look at the amout of work/lines of code/whatever which is shared between all cases vs. the amount per case statement.

public void method(int a) {
  // n-pre lines of code
  switch (a) {
    case 1:
      // n-switch lines of code
      break;
    case 2:
      // n-switch lines of code
      break;
    // some more cases
    default:
      break;
    }
  // n-post lines of code
}

If in this case n-pre or n-post are significantly larger than n-switch than I don’t think you could call the use of switch a code smell. If on the other hand n-pre/n-post are small or even worse zero, something could be wrong in the design. As soon as I find the time, I’ll try to make this into a PMD rule…


Any comments? Or questions? Just leave a Reply: