When programming, you sometimes run into situations where a simple true or false boolean value simply isn’t enough and you are looking for three possible states: yes, no or maybe.
From a software design point of view, this is achieved by introducing an enum which can hold these three values:
enum CHOICE {
YES,
NO,
MAYBE
}
CHOICE myChoice = CHOICE.MAYBE;
if (myChoice == CHOICE.YES) {
// yes
} elseif (myChoice == CHOICE.NO) {
// no
} else {
// maybe
}
But sometimes, this generates too much boilerplate code. Instead, you can use this tiny trick: use the Boolean wrapper class instead and define a Boolean value which can either be true (= yes), false (= no) or null (= maybe). As long as the value is not initialized you treat it as maybe:
Boolean choice;
if (choice == null) {
// maybe
} else if (choice) {
// yes (through auto-unboxing)
} else {
// no
}


My name is Manuel Schwarz. I work as a Security Engineer in Zurich, Switzerland. This is my private blog where I write about programming for the android platform and Java in general.

Recent comments