DEV Community

Cover image for Code Smell 156 - Implicit Else
Maxi Contieri
Maxi Contieri

Posted on • Originally published at maximilianocontieri.com

4

Code Smell 156 - Implicit Else

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

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

Right

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

  // Fail Fast
  throw new Exception('Model not found);
}
Enter fullscreen mode Exit fullscreen mode

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.

MongoDB Atlas runs apps anywhere. Try it now.

MongoDB Atlas runs apps anywhere. Try it now.

MongoDB Atlas lets you build and run modern apps anywhere—across AWS, Azure, and Google Cloud. With availability in 115+ regions, deploy near users, meet compliance, and scale confidently worldwide.

Start Free

Top comments (3)

Collapse
 
bwca profile image
Volodymyr Yepishev

But that's the bouncer pattern, no? Lot's of devs prefer it over else 🙃

Collapse
 
jonrandy profile image
Jon Randy 🎖️

The functionality of the two code samples is different

Collapse
 
mcsee profile image
Maxi Contieri

Hi

It is not a "safe refactor"
And, as long as I can see. the two possitive cases are dealt in the same way

Dev Diairies image

User Feedback & The Pivot That Saved The Project

🔥 Check out Episode 3 of Dev Diairies, following a successful Hackathon project turned startup.

Watch full video 🎥

👋 Kindness is contagious

Explore this insightful write-up, celebrated by our thriving DEV Community. Developers everywhere are invited to contribute and elevate our shared expertise.

A simple "thank you" can brighten someone’s day—leave your appreciation in the comments!

On DEV, knowledge-sharing fuels our progress and strengthens our community ties. Found this useful? A quick thank you to the author makes all the difference.

Okay