Ever wondered why people code boolean checks in if statements differently?
Example 1
This is the kind of code that fails silently because true
will always be assigned to hungry
and will cause the if statement to be true and the conditional code will always execute.
boolean hungry = Utils.isHungry();
if (hungry = true) {
/* this code will always be executed */
}
Example 2
There is no possibility of an accidental assignment here, and is probably the most readable code.
boolean hungry = Utils.isHungry();
if (hungry) {
/* make some cookies */
}
Example 3
This is the kind of code I have seen before but wondered why the developer has reversed the comparison. This is a defensive programming style, such that if in the future another developer accidentally changes ==
to =
then the code will not compile because true is not a variable and the value of hungry cannot be assigned to it.
boolean hungry = Utils.isHungry();
if (true == hungry) {
/* make some cookies */
}
In my opinion Example 2 is the cleanest, but now I at least realise why other developers might choose to use the style of Example 3.