Tips For Using Java booleans

12 AM May 30, 2003

The full implications of the concept of a boolean value eludes many novice Java programmers. Perhaps this is because some other languages1 have expressions with boolean results, but cannot store these in results in variables or parameters.

For instance, just today I came across an if statement like this:

    if (oneObject.isFlagSet() == true) {
        anotherObject.setFlagX(true);
        anotherObject.setFlagY(true);
    } else {
        anotherObject.setFlagX(false);
        anotherObject.setFlagY(false);
    }

It took a few seconds for the precise meaning to sink in. First, consider that the if statement’s condition expression3 must be a boolean. For this reason, a program will often use an operator that produces a boolean result, such as ==, like this:

    if (a == b) {
        ...

In our case, oneObject.isFlagSet() already is a boolean, so there is no need to compare it to another value. Explicitly comparing it to true is at best useless, and at worst confusing. It would be better to write:

    if (oneObject.isFlagSet()) {
        ...

Next, consider the body of the if and else clauses. When executing the ‘if’ part, the condition (oneObject.isFlagSet()) must be true, and when executing the ‘else’ part, it must be false. We can therefore4 re-write the original if statement as:

    anotherObject.setFlagX(oneObject.isFlagSet());
    anotherObject.setFlagY(oneObject.isFlagSet());

Hey Presto! Seven lines of code into two, and the result is arguably more readable, understandable and maintainable.

Please pass this tip on to anyone that would benefit from it.

1 COBOL and SQL spring to mind here.

2 C, (older versions of) C++ and (older versions of) Python do not have a boolean type, though they can treat other variable values as booleans.

3 The bit in the brackets after the if.

4 Assuming that calling oneObject.isFlagSet() has no side-effects.

By alang | # | Comments (0)
(Posted to Software Development)

Comments

Add Comment




(Not displayed)






(Leave blank line between paragraphs. URLs converted to links. HTML stripped. Indented source code will be formatted with <pre> tags.)




© 2003-2006 Alan Green