Code Smell 101 - Comparison Against Booleans
·Nov 11, 2021·
2 min read
Play this article
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
The least surprise principle violation.
Fail Fast principle violation
Don't mix booleans with boolean castable obejcts
Many languages cast values to boolean crossing domains.
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
if false ; then echo "True" else echo "False" fi # this evaluates to false
Linters can check for explicit comparisons and warnings.
It is a common industry practice to use many non booleans as booleans.
We should be very strict when using booleans.
Photo by Michael Held on Unsplash
If it doesn’t work, it doesn’t matter how fast it doesn’t work.
This article is part of the CodeSmell Series.