HomeCloud ComputingBooleans thought-about dangerous | InfoWorld

Booleans thought-about dangerous | InfoWorld




perform saveUser(
  person: Person,
  emailOption: WelcomeEmailOption,
  verificationStatus: VerificationStatus
): void {
  if (emailOption === WelcomeEmailOption.Ship) {
    sendEmail(person.e mail, 'Welcome!');
  }
  if (verificationStatus === VerificationStatus.Verified) {
    person.verified = true;
  }
  // save person to database...
}

And you may name it like this:


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

Isn’t that lots simpler in your mind? That decision reads like documentation. It’s clear and to the purpose, and the maintainer can see instantly what the decision does and what the parameters imply. 

Booleans are a lure for future complexity

A bonus of enums is they’re expandable. Think about you’ve gotten a meals and beverage system that has small and enormous sized drinks. You would possibly find yourself with


var IsSmallDrink: boolean;

And also you construct your system round that Boolean variable, even having Boolean fields within the database for that data. However then the boss comes alongside and says, “Hey, we’re going to begin promoting medium drinks!”

Uh oh, that is going to be a significant change. Instantly, a easy Boolean has turn into a legal responsibility. However if you happen to had averted Booleans and began with


enum DrinkSize {
  Small,
  Giant
}

Then including one other drink dimension turns into a lot simpler.

Look, Booleans are highly effective and easy. I’m sufficiently old to recollect when languages didn’t even have Boolean varieties. We needed 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 perceive their enchantment. However utilizing Booleans finally ends up being fraught with peril. Are there exceptions? Certain, there are easy circumstances the place issues truly are and all the time might be both true or false—like isLoading. However if you’re in a rush, otherwise you let your guard down, or possibly you’re feeling a bit lazy, you may simply fall into the lure of writing convoluted, hard-to-reason-about code. So tread frivolously and punctiliously earlier than utilizing a Boolean variable.

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

- Advertisment -
Google search engine

Most Popular

Recent Comments