DEV Community

Cover image for Code Smell 101 - Comparison Against Booleans
Maxi Contieri
Maxi Contieri

Posted on • Originally published at maximilianocontieri.com

3 1

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
Enter fullscreen mode Exit fullscreen mode

Right

#!/bin/bash

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

# this evaluates to false   
Enter fullscreen mode Exit fullscreen mode

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

More Info

Credits

Photo by Michael Held on Unsplash


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

Mich Ravera


This article is part of the CodeSmell Series.

Build gen AI apps that run anywhere with MongoDB Atlas

Build gen AI apps that run anywhere with MongoDB Atlas

MongoDB Atlas bundles vector search and a flexible document model so developers can build, scale, and run gen AI apps without juggling multiple databases. From LLM to semantic search, Atlas streamlines AI architecture. Start free today.

Start Free

Top comments (0)

Runner H image

Automate Your Workflow in Slack, Gmail, Notion & more

Runner H connects to your favorite tools and handles repetitive tasks for you. Save hours daily. Try it free while it’s in beta.

Try for Free

👋 Kindness is contagious

Dive into this thoughtful piece, beloved in the supportive DEV Community. Coders of every background are invited to share and elevate our collective know-how.

A sincere "thank you" can brighten someone's day—leave your appreciation below!

On DEV, sharing knowledge smooths our journey and tightens our community bonds. Enjoyed this? A quick thank you to the author is hugely appreciated.

Okay