Skip to content

Booleans Considered Harmful: 5 Rules for Cleaner, More Readable Code

  • News

“`html

Booleans: Simple But Sneaky!

Have you ever heard of “Booleans” in computer programming? They seem super simple at first – just “true” or “false,” like a light switch that’s either on or off. But trust me, they can get complicated fast!

After coding for years, I’ve learned to be careful when using Booleans. Some programmers might like them, but I believe it’s best to avoid them if possible, or at least use them very carefully.

Booleans can make your code confusing if you’re not careful, with all the “not”s and “and”s and “greater than”s. It’s like trying to untangle a messy ball of yarn! But they are important, so let’s explore how to use them wisely.

Rule #1: Stay Positive!

When naming your Boolean variables (think of a variable as a container holding information), try to give them positive names. This means the variable should be “true” when things are working correctly. For example:

if UserIsAuthorized {
  // Do something
}

This is much easier to understand than something like:

if !UserIsNotAuthorized {
  // Do something
}

Using “not” and double negatives can be confusing. It’s easier to think positively!

Lila: John, what’s a “variable” in this case? It sounds like something from math class!

John: Good question, Lila! In programming, a variable is like a labeled box where you can store information. In this case, the box labeled “UserIsAuthorized” can hold either “true” or “false,” indicating whether a user is allowed access.

Rule #2: Put the Positive First

If you’re using an “if…else” statement (which is like saying, “if this is true, do this; otherwise, do that”), put the positive part first. Our brains like to follow the “happy path.” So, instead of this:

if not Authorized {
  // bad stuff
} else {
  // good stuff
}

Do this:

if Authorized {
  // Things are okay
} else {
  // Go away!!
}

It’s easier to read and understand when the positive case comes first. It avoids making your brain do extra work figuring out the “not.”

Rule #3: No Complex Expressions

Explaining variables are greatly underused. It might seem faster to write everything in one go, but it’s always worth taking the time to “show your work,” like your math teacher used to say. Only use AND (&&) and OR (||) between named variables, never raw expressions.

Instead of a complicated line like this:

if (user.age > 18 && user.isActive && !user.isBanned && user.subscriptionLevel >= 2) {
  grantAccess();
}

Break it down into smaller, easier-to-understand pieces:

const isAdult = user.age > 18;
const hasAccess = !user.isBanned;
const isActive = user.isActive;
const isSubscriber = user.subscriptionLevel >= 2;

const canAccess = isAdult && hasAccess && isActive && isSubscriber;

if (canAccess) {
  grantAccess();
}

This is much clearer and easier to read. Don’t be afraid to make the explaining variables really obvious! Clarity is more important than saving a few keystrokes.

const userHasJumpedThroughAllTheRequiredHoops = true;

Also, these explaining variables are great for testing and debugging.

Lila: Okay, that makes sense. It’s like breaking down a long sentence into smaller, easier-to-understand phrases. But what are “AND” and “OR” in this context?

John: Exactly, Lila! “AND” (&&) means that *both* things on either side of it must be true for the whole statement to be true. “OR” (||) means that *at least one* of the things on either side of it must be true for the whole statement to be true. So, in the example, to “grantAccess,” the user must be an adult AND have access AND be active AND be a subscriber.

Rule #4: Say No to Boolean Parameters

Using Booleans as parameters (inputs) in functions (a block of code that performs a specific task) can be very confusing. For example:

saveUser(user, true, false); // ...the heck does this even mean?

When you write the function, it’s clear what the parameters mean. But when someone else (or you, later!) has to use it, they have to go look up the function definition to understand what those “true” and “false” values mean.

Instead, avoid Booleans altogether and use something called an “enum” (short for enumeration). An enum is like a list of named values.

enum WelcomeEmailOption {
  Send,
  DoNotSend,
}

enum VerificationStatus {
  Verified,
  Unverified,
}

Then your function can look like this:

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

And you can call it like this:

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

Isn’t that much easier to understand? It reads like documentation! It’s clear what the call does and what the parameters mean.

Lila: Enums sound useful! So instead of just saying “true” or “false,” you’re giving those values more specific names?

John: Exactly! It’s like instead of saying “go left” or “go right” at a fork in the road, you’re saying “take the road to Grandma’s house” or “take the road to the grocery store.” It’s much more informative!

Rule #5: Booleans Are a Trap for Future Complexity

Enums have another advantage: they’re expandable. Imagine you have a drink ordering system with small and large sizes. You might use a Boolean:

var IsSmallDrink: boolean;

But what happens when your boss says, “We’re adding medium-sized drinks!” Suddenly, that simple Boolean isn’t enough. You’d have to make major changes to your code.

But if you had started with an enum:

enum DrinkSize {
  Small,
  Large
}

Then adding a medium size is much easier. You just add it to the enum!

Final Thoughts

Booleans are powerful, but they can also be dangerous if you’re not careful. They can lead to convoluted and hard-to-understand code. So, tread lightly and carefully before using a Boolean variable.

Personally, I find these rules helpful in keeping my code clean and understandable. It’s all about making things easier for yourself and others in the long run.

Lila: As a beginner, this all seems a bit overwhelming! But I can definitely see how being clear and organized from the start can save a lot of headaches later on. I’ll try to remember these tips when I start coding!

This article is based on the following original source, summarized from the author’s perspective:
Booleans considered harmful

“`

Related Posts

Leave a Reply

Your email address will not be published. Required fields are marked *