This content originally appeared on DEV Community and was authored by 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
Return a boolean proposition instead of checking a negation.
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;
}
Right
function canWeMoveOn() {
return !work.hasPendingTasks();
}
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
Code Smell 101 - Comparison Against Booleans
Maxi Contieri ・ Nov 11 '21 ・ 2 min read
Code Smell 24 - Boolean Coercions
Maxi Contieri ・ Nov 14 '20 ・ 2 min read
Code Smell 62 - Flag Variables
Maxi Contieri ・ Feb 8 '21 ・ 1 min read
Code Smell 102 - Arrow Code
Maxi Contieri ・ Nov 15 '21 ・ 2 min read
Code Smell 51 - Double Negatives
Maxi Contieri ・ Dec 24 '20 ・ 1 min read
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
Software Engineering Great Quotes
Maxi Contieri ・ Dec 28 '20 ・ 13 min read
This article is part of the CodeSmell Series.
How to Find the Stinky parts of your Code
Maxi Contieri ・ May 21 '21 ・ 4 min read
This content originally appeared on DEV Community and was authored by DEV Community
DEV Community | Sciencx (2022-03-05T15:29:25+00:00) Code Smell 118 – Return False. Retrieved from https://www.scien.cx/2022/03/05/code-smell-118-return-false/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.