Prefer Enums and Avoid Booleans

An enumerator is a data type consisting of a set of named values that can be used in a type-safe way. While it may not look as simple as a boolean, using an enum or other user-defined type helps us avoid setting up complicated if statements with multiple branches.

enum UserStates{ case active

case inactive

case blocked

case expired }

Let’s look at the benefits an enum brings to the table when managing finite states and function signatures.

1. Enums are clear and descriptive

Enums force you to name all states, which makes it easy to understand what they mean — thereby creating a self-documenting code. Also, enums clearly indicate that the values are mutually exclusive, thereby removing doubts of conflicting states. Passing enums as parameters in functions is much clearer and helps us avoid mystery booleans. Just compare the two lines below:

setUserState(true, false, false) //The version below is more concise and clearer. setUserState(UserStates.active)

2. Enums make scaling and refactoring easier

It’s easier to expand the set of values in enumerators because, unlike with a boolean, the number of possible state combinations doesn’t double with every new case. Moreover, a lot of compilers are smart enough to indicate the changes you need to make to accommodate the new enum case. For example, Swift would raise an error. At the same time, in other languages, it’s easy to look up all the cases present in an enum.

Extending an already existing enum with an additional new case requires minimal effort since the data type remains the same. This makes refactoring a whole lot easier.

3. Enums are type-safe

With enums, you cannot assign any value besides the specified ones because they are type-safe. This makes it impossible to accidentally swap values or pass an invalid state because the compiler would spot it.

Not all languages have native enum support and you could create custom types in such cases. For example, in JavaScript, we can work around this by “freezing” constants in an object: