Nelz's Blog

Mah blogginess

The Life of a Boolean

Java booleans came up in conversation today, and I wanted to point out a couple of things that I’ve noticed.

Firstly, when talking about (capital ‘B’) Booleans, it is possible to achieve a trinary state object: TRUE/FALSE/null. However, it is not recommended. In fact, I’d go so far as to recommend breaking the fingers of anyone who tried to perpetrate this horrible pattern in your code.

Secondly, I’d like to discuss booleans in your model objects. I agree that it frequently seems like a good idea to include one in your model object. However, I have seen so many occurrences where, over time, it becomes necessary to add a third (or fourth, or fifth) state. Even the RDBMSes are hedging their bets by storing boolean flags as TINYINTs. I would suggest that you seriously consider using an Enum to represent your two states as they exist at the beginning of their lifecycle… This way you won’t get stuck with a bunch of isXXX() accessors that all have to be refactored as soon as you add a third state.