Skip to content

Latest commit

 

History

History
110 lines (64 loc) · 2.45 KB

File metadata and controls

110 lines (64 loc) · 2.45 KB

Code Smell 101 - Comparison Against Booleans

Code Smell 101 - Comparison Against Booleans

When comparing to booleans, we perform magic castings and get unexpected results.

TL;DR: Don't compare against true. Either you are true, or false or you shouldn't compare

Problems

  • Hidden castings

  • The least surprise principle violation.

  • Fail Fast principle violation

Solutions

  1. Use booleans

  2. Don't mix booleans with boolean castable objects

Context

Many languages cast values to boolean crossing domains.

Sample Code

Wrong

#!/bin/bash

if [ false ]; then
    echo "True"
else
    echo "False"
fi

# this evaluates to true since 
# "false" is a non-empty string

if [ false ] = true; then
    echo "True"
else
    echo "False"
fi

# this also evaluates to true

Right

#!/bin/bash

if  false ; then
    echo "True"
else
    echo "False"
fi

# this evaluates to false

Detection

[X] Automatic

Linters can check for explicit comparisons and warnings.

Tags

  • Castings

Conclusion

It is a common industry practice to use many non booleans as booleans.

We should be very strict when using booleans.

Relations

Code Smell 69 - Big Bang (JavaScript Ridiculous Castings)

More Info

Fail Fast

Credits

Photo by Michael Held on Unsplash


If it doesn’t work, it doesn’t matter how fast it doesn’t work.

Mich Ravera

Software Engineering Great Quotes


This article is part of the CodeSmell Series.

How to Find the Stinky Parts of your Code