Code Smell 24 - Boolean Coercions

Code Smell 24 - Boolean Coercions

Maxi Contieri
·Nov 14, 2020·

2 min read

Subscribe to my newsletter and never miss my upcoming articles

Play this article

Booleans should be just True and false

TL;DR: Don't do magic castings to boolean. You will regret on a friday night.

Problems

  • Hiding Errors

  • Accidental complexity coupled to one particular language.

  • Readability

  • Difficulty to hop among languages.

  • IFs

Solutions

  1. Be explicit.

  2. Work with booleans for boolean conditions. Not integers, not nulls, not strings, not lists. Just booleans.

  3. Fail fast

Sample Code

Wrong

virus = ['MERS', 'SARS']
vaccines = []

if vaccines:
    print ("let's get vaccinated")
else:
    print ("We have no vaccines yet. Keep researching")

if virus:
    print ("There are some virus around. Take extra care")
else:
    print ("We are free to get out. Not masks are necessary")

#equivalent     

if not vaccines:
    print ("We have no vaccines yet. Keep researching")
else:
    print ("let's get vaccinated")

if not virus:
    print ("We are free to get out. Not masks are necessary")
else:
    print ("There are some virus around. Take extra care")
if len(vaccines) == 0:
    print ("We have no vaccines yet. Keep researching")
else:
    print ("Let's get vaccinated")


if len(virus) == 0:
    print ("We are free to get out. Not masks are necessary")
else:
    print ("There are some virus around. Take extra care")

Detection

This is a language feature. Some strict languages show warnings with this magic wizardry.

Tags

  • Coercions

  • Primitive

Conclusion

Some languages encourage doing some magic abbreviations and automatic castings. This is a source of errors and a Premature Optimization warning.

We should always be as explicit as possible.

Relations

More Info


It is not the language that makes programs appear simple. It is the programmer that make the language appear simple!

Robert Martin


This article is part of the CodeSmell Series.

Last update: 2021/07/07

 
Share this

Impressum

Technical Opinions are my own. I don't have the revealed truth.

Software Design is a creative activity. These are hints and not rigid rules.

I write on BackEnd Business Systems and OOP Design. My advice/experience might not suit other systems.

You can write me at info(at)maximilianocontieri.com