MapToBooleanWithIf

Misconception:

An if statement is necessary for converting an expression such as a > b into a boolean.

Incorrect

To map a boolean expression to a boolean, an if statement is necessary

Correct

To map a boolean expression to a boolean, one can just use it

Correction
Here is what's right.

The condition to be used in an if statement has to be an expression of type boolean. Thus, that expression already will evaluate to a boolean value. Taking that boolean value and using an if statement to map from it to a boolean value is entirely unnecessary.

boolean b;
if (CONDITION) {
  b = true;
} else {
  b = false;
}

This can be refactored to:

boolean b = CONDITION;

Note that this misconception is pretty much equivalent to the existing PMD Java design rule SimplifyBooleanReturns. Thus, even professional developers seem to hold it.

Origin
Where could this misconception come from?

This misconception may stem from the student doing a case analysis:

  • If the condition is true, what do we want to do?
  • If the condition is false, what do we want to do?

Originally, each case may do more than just return a boolean value. But due to some simplification, the cases then reduce to just a boolean value, resulting in this kind of code.

Some students do not seem to recognize that the simplified version is equivalent to the version using the if statement.

Symptoms
How do you know your students might have this misconception?

In the following examples, assume that CONDITION is some expression of type boolean (e.g., isHappy, i < length, o != null, pacman.isHungry(), or a && b).

Example: Assignment

boolean b;
if (CONDITION) {
  b = true;
} else {
  b = false;
}

Example: Return

if (CONDITION) {
  return true;
} else {
  return false;
}

Stay up-to-date

Follow us on  twitter to hear about new misconceptions.