Code Smell 115 - Return True

Code Smell 115 - Return True

Booleans are natural code smells. Returning and casting them is sometimes a mistake

TL;DR: Don't return true or false. Be declarative.

Problems

  • Readability

  • Primitive Obsession

  • If/Else abuse

Solutions

  1. Return truth value in a declarative way

  2. Replace IF With polymorphism.

Context

Dealing with low-level abstractions, we usually return booleans.

When we create complex and mature software, we start to forget about this primitive obsession and care about real-world rules and identities

Sample Code

Wrong

boolean isEven(int num){
     if(num%2 == 0){
       return true;
    } else {
       return false;}        
}

Right

boolean isEven(int numberToCheck){
  //We decouple the what (to check for even or odd)
  //With how (the algorithm)
  return (numberToCheck % 2 == 0);     
}

Detection

[X] Automatic

Many linters can check syntactic trees and look for explicit true/value returns

Tags

  • Primitive

Conclusion

Search on code libraries for return true statements and try to replace them when possible.

Relations

More Info

Credits

Photo by engin akyurt on Unsplash


The good news is: Anything is possible on your computer. The bad news is: Nothing is easy.

Ted Nelson


This article is part of the CodeSmell Series.