Code Smell 24 - Boolean Coercions
Booleans should be just True and False

I’m a senior software engineer loving clean code, and declarative designs. S.O.L.I.D. and agile methodologies fan.
Search for a command to run...
Booleans should be just True and False

I’m a senior software engineer loving clean code, and declarative designs. S.O.L.I.D. and agile methodologies fan.
No comments yet. Be the first to comment.
In this series, we will see several symptoms and situations that make us doubt the quality of our developments. We will present possible solutions. Most are just clues. They are no hard rules.
Approve the logic once, then let it run the same way forever.

Different stages need different brains.

One Second Brain doesn't scale past one skull.

Style errors double when nobody enforces them.

Know who speaks before the skill runs TL;DR: Always define a clear role at the top of every skill file so you know whose perspective drives the execution. Common Mistake ❌ You write a skill full of

Booleans should be just True and False
TL;DR: Don't do magic castings to boolean. You will regret it on a Friday night.
Hiding Errors
Accidental complexity coupled with one particular language.
Readability
Difficulty hopping among languages.
Be explicit.
Work with booleans for boolean conditions. Not integers, not nulls, not strings, not lists. Just booleans.
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")
This is a language feature. Some strict languages show warnings with this magic wizardry.
Coercions
Primitive
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.
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