Possible Duplicate:
Is it bad to explicitly compare against boolean constants e.g. if (b == false) in Java?
In this NotePadProvider sample code, I noticed that the author chose the form:
if (values.containsKey(NoteColumns.CREATED_DATE) == false) {
values.put(NoteColumns.CREATED_DATE, now);
}
Over:
if (!values.containsKey(NoteColumns.CREATED_DATE)) {
values.put(NoteColumns.CREATED_DATE, now);
}
Is there any advantage in the first form over the more logical one?
It's the logical negation operator. The ! operator computes logical negation of its operand. That is, it produces true, if the operand evaluates to false, and false, if the operand evaluates to true.
Boolean values are values that evaluate to either true or false , and are represented by the boolean data type. Boolean expressions are very similar to mathematical expressions, but instead of using mathematical operators such as "+" or "-", you use comparative or boolean operators such as "==" or "!".
To add clarity, the == is a comparison operator. By the rule of order of operations parentheses are processed first. So the boolean expression (false or true) evaluates to True. Then the expression is evaluated as false == true.
Notice that the boolean in the if-test (true or false) happens to be the same as the value we want to return. If the test value is true, we return true. If the test value is false, we return false. So just return the test value directly!
Apart from "readability", no. They're functionally equivalent.
("Readability" is in quotes because I hate == false
and find !
much more readable. But others don't.)
Mostly READABILITY. When reading others code, it is much more intuitive to read as NOT CONTAINS KEY !values.containsKey(NoteColumns.CREATED_DATE)
instead of reading CONTAINS KEY IS FALSE (values.containsKey(NoteColumns.CREATED_DATE) == false)
.
This is a style choice. It does not impact the performance of the code in the least, it just makes it more verbose for the reader.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With