If you have a situation where you need to know where a boolean value wasn’t set (for example if that unset value should inherit from a parent value) the Java boolean primitive (and the equivalent in other languages) is clearly not adequate.
What’s the best practice to achieve this? Define a new simple class that is capable of expressing all three states or use the Java Boolean class and use null to indicate the unset state?
I would use that. It’s the most straight-forward.
Another way is to use an enumeration. Maybe that’s even better and faster, since no boxing is required:
There is the advantage of the first that users of your class doesn’t need to care about your three-state boolean. They can still pass
trueandfalse. If you don’t like thenull, since it’s telling rather little about its meaning here, you can still make apublic static final Boolean tralse = null;in your class.