Code Smell 118 - Return False

Maxi Contieri - Mar 5 '22 - - Dev Community

Checking for a boolean condition to return a boolean value is awkward

TL;DR: Don't return explicit booleans. Most boolean usages are code smells.

Problems

  • Declarativeness

  • Ninja Code

  • Implementative solutions

Solutions

  1. Return a boolean proposition instead of checking a negation.

  2. Answer must be a business logic formula, not an algorithm.

Context

When dealing with boolean formulas, it is more readable to show a business boolean formula than introduce a negated IF clause.

Programmers tend to return accidental implementative solutions instead of real business rules.

Sample Code

Wrong

function canWeMoveOn() {
  if (work.hasPendingTasks())
    return false;
  else
    return true;
}
Enter fullscreen mode Exit fullscreen mode

Right

function canWeMoveOn() {
  return !work.hasPendingTasks();
}
Enter fullscreen mode Exit fullscreen mode

Detection

[X] Automatic

Based on syntax trees, we can safely refactor the code.

Tags

  • Boolean

Conclusion

Beware of returning booleans.

After the return, you will need an If statement which is also a code smell.

Relations

More Info

Credits

Photo by Morgan Housel on Unsplash

Thanks to Nico K. for this suggestion.


It's not at all important to get it right the first time. It's vitally important to get it right the last time.

Andrew Hunt


This article is part of the CodeSmell Series.

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .