Code Smell 156 - Implicit Else

Photo by Elena Mozhvilo on Unsplash

Code Smell 156 - Implicit Else

We learn if/else on our first programming day. Then we forget the else

Maxi Contieri
·Aug 6, 2022·

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: Be explicit. Even with Else.

Problems

Solutions

  1. Write the explicit else

Context

If we early return on an IF sentence we can omit the else part.

Afterward, we Remove the IF and use polymorphism.

That is when we miss the real cases.

Sample Code

Wrong

function carBrandImplicit(model) {
  if (model === 'A4') {
    return 'audi';
  }
  return 'Mercedes-Benz';
}

Right

function carBrandExplicit(model) {
  if (model === 'A4') {
    return 'audi';
  }
  if (model === 'AMG') {
    return 'Mercedes-Benz';
  }

  // Fail Fast
  throw new Exception('Model not found);
}

Detection

[X] Automatic

We can check syntax trees and parse them and warn for missing else.

We can also rewrite them and perform mutation testing.

Tags

  • Conditionals

Conclusion

This kind of smell brings a lot of public debate, and hate.

We must exchange opinions and value each pros and cons.

Relations

More Info

Stop Using Implicit Else

When To Use Implicit Else

Credits

Photo by Elena Mozhvilo on Unsplash


The biggest issue on software teams is making sure everyone understands what everyone else is doing.

Martin Fowler


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