12.5 C
New York
Wednesday, May 21, 2025

Booleans considered harmful | InfoWorld




function saveUser(
  user: User,
  emailOption: WelcomeEmailOption,
  verificationStatus: VerificationStatus
): void {
  if (emailOption === WelcomeEmailOption.Send) {
    sendEmail(user.email, 'Welcome!');
  }
  if (verificationStatus === VerificationStatus.Verified) {
    user.verified = true;
  }
  // save user to database...
}

And you can call it like this:


saveUser(newUser, WelcomeEmailOption.Send, VerificationStatus.Unverified); 

Isn’t that a lot easier on your brain? That call reads like documentation. It’s clear and to the point, and the maintainer can see immediately what the call does and what the parameters mean. 

Booleans are a trap for future complexity

An advantage of enums is they are expandable. Imagine you have a food and beverage system that has small and large sized drinks. You might end up with


var IsSmallDrink: boolean;

And you build your system around that Boolean variable, even having Boolean fields in the database for that information. But then the boss comes along and says, “Hey, we are going to start selling medium drinks!”

Uh oh, this is going to be a major change. Suddenly, a simple Boolean has become a liability. But if you had avoided Booleans and started with


enum DrinkSize {
  Small,
  Large
}

Then adding another drink size becomes much easier.

Look, Booleans are powerful and simple. I’m old enough to remember when languages didn’t even have Boolean types. We had to simulate them with integers:


10 LET FLAG = 0
20 IF FLAG = 1 THEN PRINT "YOU WILL NEVER SEE THIS"
30 LET FLAG = 1
40 IF FLAG = 1 THEN PRINT "NOW IT PRINTS"
50 END

So I understand their appeal. But using Booleans ends up being fraught with peril. Are there exceptions? Sure, there are simple cases where things actually are and always will be either true or false—like isLoading. But if you are in a hurry, or you let your guard down, or maybe you feel a bit lazy, you can easily fall into the trap of writing convoluted, hard-to-reason-about code. So tread lightly and carefully before using a Boolean variable.

Related Articles

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Latest Articles