Nullable booleans reconsidered

If you’re about to use a Nullable<bool>, I would consider using an Enum or other data structure instead. It may help you avoid mistakes when the meaning of NULL is not known.

Recently, I mishandled a Nullable<bool>. I won’t go into the details of the mistake, but lets just say it was bad enough to require a full rollback. I began to wonder how practical it is to use in most applications. (In part in an attempt to hold on to my broken pride as a result of the stupid mistake 🙂 )

In this stackoverflow post, the answer by “Lee” provides a good example of when to use a Nullable<bool> type:

Something can be true, false or undefined for many reasons. How would one answer “Is your third child a girl?” if one only has two children? Both true and false are incorrect. Null would be appropriate as saying that the comparison doesn’t apply.”

This seems to make sense, but the more time I spend with it, the answer becomes FALSE in practice instead of NULL. NULL is just too fuzzy.

Before answering this question one would have to assign a very specific meaning to NULL. Does NULL mean there was an error in the calculation? What if there is an error in the calculation before it is determined that there are only two children? (I would also argue that if there are indeed only two children, this could be handled before the question was posed to the program.)

Because we do not know what NULL means and because it is most definitely not TRUE (because, how could it be?)  the BEST answer is FALSE.

Also, if this question indeed returns NULL, we’ve introduced a new definition to the domain. What is the scope of this definition?

So it would appear that TRUE or FALSE states represent a certainty regarding an outcome. NULL can be conceived of in at least three different states.  For example, the statement “Thomas went to the bar last night.”

  1. TRUE – Yes, Thomas went to the bar. (likeliest answer if you knew Thomas)
  2. FALSE – No, Thomas did not go to the bar.
  3. NULL – Huh?
    1. Knowable – Something went wrong in the first calculation. E.g. you asked Thomas the question but sneezed while he replied , rendering you deaf momentarily. Simply asking him again will get you the answer.
    2. Unknowable – The bar burned down and Thomas skipped town. There is no realistic way of getting the answer. (Please don’t poke holes in this, but I know you will)
    3. Not applicable – See the example above regarding the three children, but, bars and Thomases instead.

What does NULL mean here? Determining what NULL means must be performed on a case by case basis. This is why I believe it is often better to use an Enum or other structure as it more gracefully exposes the intention behind a non-binary return value.

Here is a rough example of what could be done:

Thanks for reading!!!

Leave a Reply

Your email address will not be published. Required fields are marked *