Of Enums and Booleans

In programming, we often deal with things being in a state. Users being verified, Modals being open, Posts being published. Yesterday I had an interesting chat with Daniel about rules to decide when you should store state as an enum or as a boolean. We both know that it's always better to use enums instead of booleans. It's a common advice and nothing new, just search it on the internet and you'll see countless articles recommending the use of enums.

But how can we tell that a boolean should rather be an enum?

Having a rule for such decisions not only helps you to write consistently good code – it helps you a lot in Code Reviews. "I think this boolean should be an enum instead" could be a good code improvement, but it's not a good suggestion because it doesn't contain an objective reason why it would be better.

For example, when deciding if a value should be a number or a string, there's an easy rule: if it makes sense to increment or decrement the value, it's a number. If not, it's a string which happens to only consist of numbers.

The Rule if State is an Enum or a Boolean

In short: A boolean state is the answer to a question that you ask an enum. It can also be the answer to a combination of different values, and not only enums. But if you don't have an enum to ask that question, there can't be an answer, so you need an enum.

When differentiating between different states of a thing, you ask that thing "What are you?". The answer is always an enum. You cannot answer "What are you?" with "yes". But you can ask this enum "Are you [...]?", which you can answer with "yes".

For example, a user could be verified and unverified, and also maybe blocked and deleted. You can ask this enum:

  • Are you verified? When it's verified
  • Are you unverified? When it's unverified
  • Are you able to login at all? When it's not blocked or deleted

Let's say you've modelled this as booleans isVerified and isUnverified. Managing both of them independent from each other – not by asking an enum – can cause that both are true, which is an impossible state.

You can never go wrong with storing state in an enum, even if your enum only contains 2 values. It might contain more values in the future, or it might not. But no matter what, your code stays nice and readable, and will have less cognitive load.

Footnotes