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
Return truth value in a declarative way
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
Code Smell 36 - Switch/case/elseif/else/if statements
Maxi Contieri ・ Nov 28 '20
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
Software Engineering Great Quotes
Maxi Contieri ・ Dec 28 '20
This article is part of the CodeSmell Series.