Boolean Blindness : Don't represent state with boolean !

Boolean Blindness : Don't represent state with boolean !

Hi Developers, let's talk about "Boolean blindness" and why you should avoid using boolean to manage states in your application.

If I come up to you and asking “True” or “False” ? You won’t be able to answer (you’ll be wondering about the context of my question).

True or False means nothing without additional context, so let look at another example.

val bool = true

You can’t know what information does this variable represent.

But if I write

val bool = true


val dataIsLoading = true

You can see that much of the meaning of a boolean comes from documentation around that boolean.

This can be called blind value, and that value can cause unintended consequences on refactoring our code (since many of us spend time refactoring our code).

I’m not saying boolean are bad or neither discouraging you from using them, but I’m saying we should tend to use more expressive types.

Another fact is that boolean can only have 2 values (True or False), in the above snippet we can track our value to know if the data is loading or not, but if we want to check if it’s successfully loaded we must add another Boolean variable to track this state, same for failure, etc.

As David Luposchainsky said in his book "Algebraic blindness" :

“When you have lots of faceless data types in your code, consider painting them with their domain meanings. Make them distinct, make them memorable, make them maintainable.”

So let's see a simple example of how you can paint data with their domain meaning, you can use enumeration or sealed class.

sealed class DataState {
    object Loading : DataState
    data class Success(val data: Data) : DataState
    data class Error(val error: Throwable) : DataState

Val bool = data is DataState.Loading

I hope this article was helpful, even though it's no long as it should be !

Some references :