Skip to content

Latest commit

 

History

History
101 lines (57 loc) · 3.07 KB

File metadata and controls

101 lines (57 loc) · 3.07 KB

Code Smell 199 - Gratuitous Booleans

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:
    # This code was left on debugging and passed
    # by mistake during code reviews
    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 115 - Return True

Code Smell 118 - Return False

Code Smell 101 - Comparison Against Booleans

More Info

How to Get Rid of Annoying IFs Forever

SonarSource

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


This article is part of the CodeSmell Series.

How to Find the Stinky Parts of your Code