DEV Community

Cover image for Code Smell 07 - Boolean Variables
Maxi Contieri
Maxi Contieri

Posted on • Updated on

Code Smell 07 - Boolean Variables

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) {
    //...
}
Enter fullscreen mode Exit fullscreen mode

Right

<?

function processBatch(
    LoginStrategy $login,
    DeletionPolicy $deletionPolicy,
    Date $cutoffDate) {
    //...
}
Enter fullscreen mode Exit fullscreen mode

Detection

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

Relations

Some languages have issues with boolean comparators.