Yes, no or maybe?

Posted by on May 14, 2011 in Java | 0 comments

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
}

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>