
Using boolean variables as flags, exposes accidental implementation and pollutes the code with Ifs.
TL;DR: Don't use boolean variables, they force you to write Ifs. Create polymorphic states instead.
Problems
Extensibility
Comparison in some languages
Solutions
- If Boolean maps to a real world entity is safe. Otherwise, model as a State to favor Extensibility. This also follows Open/Closed Principle.
Examples
- Flags
Exceptions
- Real world true/false rules
Sample Code
Wrong
<?
function processBatch(
bool $useLogin,
bool $deleteEntries,
bool $beforeToday) {
//...
}
Right
<?
function processBatch(
LoginStrategy $login,
DeletionPolicy $deletionPolicy,
Date $cutoffDate) {
//...
}
Detection
Automatic detection can warn for boolean usage, but this can yield false positives.
Relations
Some languages have issues with boolean comparators.
![0_QjZ76_c6hmi1UfXc[1].jpg](https://cdn.hashnode.com/res/hashnode/image/upload/v1603587404705/M5_udJ8Cw.jpeg)
In these coupled with accidental complexity languages, booleans are a common error source.
Also Known as
- Flag Abuser
Tags
Declarative
Primitive
More info
Conclusion
Take extra care when declaring something boolean. Flags are difficult to maintain and extend. Learn more about the domain. Try migrating to state design pattern. Use polymorphism instead of ifs/switch/cases.
Credits
Photo by Phil Hearing on Unsplash
These tweets inspired this code smell:
This article is part of the CodeSmell Series.
Last update: 2021/06/08
About the author
I’m a senior software engineer loving clean code, and declarative designs. S.O.L.I.D. and agile methodologies fan.
Comments
Join the discussionNo comments yet. Be the first to comment.
Code Smells
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.





