DEV Community

Cover image for Code Smell 110 - Switches With Defaults
Maxi Contieri
Maxi Contieri

Posted on • Originally published at maximilianocontieri.com

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 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 taking decisions without evidence.

Since case and switches are also an 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 value does not presently match the above values
    //or future values
    //the following will be executed
    doSomethingSpecial();
    break;
}
Enter fullscreen mode Exit fullscreen mode

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;
}
Enter fullscreen mode Exit fullscreen mode

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.

Top comments (0)