Software Development

Three Corners of Boolean

Let’s be honest, no good ever came out of a null boolean value!

However, it’s common for boolean to prove not quite good enough to represent what’s going on. This is where you’re dealing with a false dichotomy in something.

I’m reminded of a potentially apocryphal story about a UK politician:

Him: the problem is that half of them are crooks
Speaker: please withdraw that comment
Him: ok, half of them aren’t crooks!

We hit a similar thing in some test code recently. We want to detect whether the images have loaded on a front end screen. We have the front-end detect any failures in loading images and attaching an HTML class to images that failed to load. We were trying to detect the absence of those classes as proof that the images had loaded.

This led to a situation where if any failed to load, the test was failing, which might be a reasonable failure. In our case, however, the existence of any working image would be enough to pass the test. So we decided to add a class to the image element that said when it was loaded. We detected this from the state of no-loading-error.

This, however, led to a new problem. When the image hasn’t even started loading yet, it can’t be said to have a loading error. So how do we avoid prematurely declaring the image as loaded?

It turns out that this is potentially a tri-state. The image can be said to be loading, loaded or failed.

In our case, it might be simpler to represent this with two boolean variables, rather than one. This allows us to more simply express whether to tag it with each of the loading failed or loading succeeded classes.

This does allow 4 states, but that’s not necessarily a bad thing.

Published on Java Code Geeks with permission by Ashley Frieze, partner at our JCG program. See the original article here: Three Corners of Boolean

Opinions expressed by Java Code Geeks contributors are their own.

Ashley Frieze

Software developer, stand-up comedian, musician, writer, jolly big cheer-monkey, skeptical thinker, Doctor Who fan, lover of fine sounds
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

2 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Peter Westlin
Peter Westlin
3 years ago

…and to make thing even more interesting you can wrap your Boolean in an Optional… :D

In your case, maybe something like an enum would better suit your needs.

Ashley Frieze
3 years ago

Once you start having Optional<Boolean> you’re many levels deep and need to rethink.

In this particular example, owing to the system we were using, an enum wasn’t possible. Often a multi-state SHOULD be an enum, but enum can be overused and can end up containing states that read as TRUE, FALSE, UNKNOWN, which makes you think you may as well have used boolean in a clear way.

Back to top button