Code Smell 110 - Switches With Defaults

Photo by Joshua Woroniecki on Unsplash

Code Smell 110 - Switches With Defaults

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

Maxi Contieri
·Dec 15, 2021·

2 min read

Subscribe to my newsletter and never miss my upcoming articles

Play this article

Table of contents

  • Problems
  • Solutions
  • Context
  • Sample Code
  • Detection
  • Tags
  • Conclusion
  • Relations
  • More Info
  • Credits

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;
}

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.

 
Share this

Impressum

Technical Opinions are my own. I don't have the revealed truth.

Software Design is a creative activity. These are hints and not rigid rules.

I write on BackEnd Business Systems and OOP Design. My advice/experience might not suit other systems.

You can write me at info(at)maximilianocontieri.com