skies.dev

Why You Should Stop Using Booleans

2 min read

I have nothing against booleans. They are compact, fast, and useful when the answer is truly yes or no.

The problem is that a boolean often throws away information you may want later.

Archived records

If you want to mark a post as archived, a boolean works:

interface Post {
  isArchived: boolean;
}

But a timestamp carries more value:

interface Post {
  archivedAt?: Date;
}

Now you can answer two questions:

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

You know whether the post is archived, and you know when it happened.

User roles

Booleans also break down when you have more than one state. If a user can be an admin today and a moderator tomorrow, two flags become awkward:

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

An enum is clearer:

enum UserRole {
  Admin,
  Moderator,
}

interface User {
  role: UserRole;
}

This keeps the valid states in one place and makes the model easier to extend.

Tradeoffs

This is not a blanket rule. Booleans are smaller than timestamps or enums, and that can matter in storage-heavy systems.

For most application code, though, the better question is: what is the most expressive type for this data? If a timestamp or enum tells the truth more clearly than a boolean, use it.

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