Code Smell 199 - Gratuitous Booleans
Maxi Contieri
Posted on March 6, 2023
A code that either returns or no returns at all
TL;DR: Check carefully your boolean expressions
Problems
Readability
Possible Defects
Solutions
- Refactor and remove obsolete code
Context
When a function is designed to return an invariant value, it may be poor design, but it shouldn’t adversely affect the outcome of your program. However, when it happens on all paths through the logic, it is likely a mistake.
This rule raises an issue when a function contains several return statements that all return the same value.
Sample Code
Wrong
# Gratuitous boolean expressions
if a > 0 and True:
print("a is positive")
else:
print("a is not positive")
Right
if a > 0:
print("a is positive")
else:
print("a is not positive")
Detection
[X] Automatic
Many linters can detect this problem by parsing execution trees.
Tags
- Complexity
Conclusion
Boolean expressions should be straightforward to read and understand.
Relations
Code Smell 101 - Comparison Against Booleans
Maxi Contieri ・ Nov 11 '21
More Info
How to Get Rid of Annoying IFs Forever
Maxi Contieri ・ Nov 9 '20
Disclaimer
Code Smells are just my opinion.
Credits
Photo by Jungwoo Hong on Unsplash
The central enemy of reliability is complexity.
Daniel Geer
Software Engineering Great Quotes
Maxi Contieri ・ Dec 28 '20
This article is part of the CodeSmell Series.
Posted on March 6, 2023
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
November 14, 2024