Code Smell 110 - Switches With Defaults

Default means 'everything we don't know yet'. We cannot foresee the future.

TL;DR: Don't add a default clause to your cases. Change it for an exception. Be Explicit.

Problems

Solutions

  1. Replace if and cases with polymorphism

  2. Change the Default code to an Exception

Context

When using cases, we usually add a default case so it doesn't fail.

Failing is always better than making decisions without evidence.

Since case and switches are also a smell, we can avoid them.

Sample Code

Wrong

switch (value) {
  case value1:
    // if value1 matches the following will be executed..
    doSomething();
    break;
  case value2:
    // if value2 matches the following will be executed..
    doSomethingElse();
    break;
  default:
    // if the value does not presently match the above values
    // or future values
    // the following will be executed
    doSomethingSpecial();
    break;
}

Right

switch (value) {
  case value1:
    //if value1 matches the following will be executed..
    doSomething();
    break;
  case value2:
    //if value2 matches the following will be executed..
    doSomethingElse();
    break;
  case value3:
  case value4:
    //We currently know these options exist
    doSomethingSpecial();
    break;
  default:
    //if value does not match the above values we need to take a decision
    throw new Exception('Unexpected case ' + value + ' we need to consider it');
    break;
}

Detection

[X] Semi Automatic

We can tell our linters to warn us on default uses unless there's an exception.

Tags

  • Fail Fast

Conclusion

Writing robust code doesn't mean we need to take decisions without evidence.

Relations

More Info

Credits

Photo by Joshua Woroniecki on Unsplash


The cost of adding a feature isn’t just the time it takes to code it. The cost also includes the addition of an obstacle to future expansion. The trick is to pick the features that don’t fight each other.

John Carmack


This article is part of the CodeSmell Series.