MapToBooleanWithConditionalOperator
The conditional operator is necessary
for converting an expression such as a > b
into a boolean
.
To map a boolean expression to a boolean, a conditional operator is necessary
To map a boolean expression to a boolean, one can just use it
CorrectionHere is what's right.
The condition to be used in a ternary conditional operator
has to be an expression of type boolean
.
Thus, that expression already will evaluate to a boolean
value.
Taking that boolean
value and using a conditional operator
to map from it to a boolean
value is entirely unnecessary.
boolean b = CONDITION ? true : false;
This can be refactored into:
boolean b = CONDITION;
OriginWhere 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 produce 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 conditional operator.
SymptomsHow 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 = CONDITION ? true : false;
Example: Return
boolean predicate() {
...
return CONDITION ? true : false;
}