Code Smell 115 — Return True

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

Maximiliano Contieri
2 min readFeb 20, 2022
Photo by engin akyurt on Unsplash

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

Problems

Solutions

1. Return truth value in a declarative way.

2. Replace IFs 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

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

Ted Nelson

--

--

Maximiliano Contieri

I’m a senior software engineer specialized in declarative designs. S.O.L.I.D. and agile methodologies fan. Maximilianocontieri.com