Best way to define true, false, unset state
In Java 8, there is also the Optional option:
public static final Optional<Boolean> TRI_TRUE = Optional.of(true);
public static final Optional<Boolean> TRI_FALSE = Optional.of(false);
public static final Optional<Boolean> TRI_UNKNOWN = Optional.empty();
As a bonus, you will get all those map and consume methods.
Boolean a = true;
Boolean b = false;
Boolean c = null;
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:
public enum ThreeState {
TRUE,
FALSE,
TRALSE
};
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 true
and false
. If you don't like the null
, since it's telling rather little about its meaning here, you can still make a public static final Boolean tralse = null;
in your class.