cover-img

Code Smell 07 - Boolean Variables

22 September, 2022

5

5

0

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 polymorfic 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

Sample Code

Wrong

Right

Detection

Automatic detection can warn for boolean usage, but this can yield false positives.

Exceptions

Real world true/false rules

Relations

Some languages have issues with boolean comparators.
img
In these coupled with accidental complexity languages, booleans are a common error source.

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.

Also Known as

Flag Abuser

Credits

These tweets inspired this code smell:
This article is part of the CodeSmell Series.

refactoring

code

cleancode

smells

5

5

0

refactoring

code

cleancode

smells

Maxi Contieri

Buenos Aires, Argentina

🎓Learn something new every day.📆 💻CS software engineer 👷coding👨🏽‍🏫teaching ✍🏾writing 🎨Software Design 🏢SOLID 🌉TDD 👴Legacy 💩Code Smells

More Articles

Showwcase is a professional tech network with over 0 users from over 150 countries. We assist tech professionals in showcasing their unique skills through dedicated profiles and connect them with top global companies for career opportunities.

© Copyright 2024. Showcase Creators Inc. All rights reserved.