DEV Community

Cover image for Code Smell 199 - Gratuitous Booleans
Maxi Contieri
Maxi Contieri

Posted on • Originally published at maximilianocontieri.com

Code Smell 199 - Gratuitous Booleans

A code that either returns or no returns at all

TL;DR: Check carefully your boolean expressions

Problems

  • Readability

  • Possible Defects

Solutions

  1. 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")

Enter fullscreen mode Exit fullscreen mode

Right

if a > 0:
    print("a is positive")
else:
    print("a is not positive")
Enter fullscreen mode Exit fullscreen mode

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

More Info

SonarSource

Disclaimer

Code Smells are just my opinion.

Credits

Photo by Jungwoo Hong on Unsplash


The central enemy of reliability is complexity.

Daniel Geer


This article is part of the CodeSmell Series.

Top comments (1)

Collapse
 
krlz profile image
krlz • Edited

Cool series, thanks for sharing