skies.dev

Why You Should Stop Using Booleans

3 min read

I have nothing against booleans. They're a compact way to represent something that's either true or false with 1 bit.

But therein lies a problem: With 1 bit, we can represent

  • true or false
  • on or off
  • yes or no

but nothing more.

What if I told you that you can pack more meaningful data by not using a boolean type.

Let me give you an example.

Archived records

Say you want to a way to mark a post in your system as archived. Your first instinct might be to use a boolean.

interface Post {
  isArchived: boolean;
}

This is cool and all, but here's a suggestion: What if we use a timestamp instead?

interface Post {
  archivedAt?: Date;
}

We can then use the timestamp to determine if a post is archived.

function isArchived(post: Post) {
  return post.archivedAt != null;
}

Now not only can we tell if a post is archived, but we can also tell when it was archived.

Here's another example.

User roles

Let's say you want a flag to tell if a user is an admin. Again your first instinct might be to use a boolean.

interface User {
  isAdmin: boolean;
}

This works. For now. But what happens if we want to add another role in our system e.g. a moderator? Are you going to have 2 booleans?

interface User {
  isAdmin: boolean;
  isModerator: boolean;
}

We could have 2 booleans, one for each role, but this is a bit (no pun intended) of a pain to manage.

For n roles, we'd have 2^n states we'd have to deal with.

So what if instead we use an enum?

enum UserRole {
  Admin,
  Moderator,
}

interface User {
  role: UserRole;
}

This is a bit (OK, pun intended) nicer. Now we can deal with all the roles in our system in a single place. Instead of having 2^n states, we have n states. One for each role.

Tradeoffs and parting thoughts

Keep in mind there's a tradeoff with using these techniques. Booleans are 1 bit. Enums might be represented as an integers (4 bytes = 32 bits). The story is similar with timestamps in that you'll need more bits to store it.

But storage is cheap. And for the vast majority of use cases, saving those bits is probably not a big deal in terms of performance or cost savings. But it's something to keep in mind.

So next time you reach for a boolean, ask yourself if there's a better data type you can use. Are you using booleans anywhere in your code where a better data type is available?

Hey, you! 🫵

Did you know I created a YouTube channel? I'll be putting out a lot of new content on web development and software engineering so make sure to subscribe.

(clap if you liked the article)

You might also like