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?
This question is related to
java
boolean
boolean-logic
boolean-expression
The first form, when used with an API that returns Boolean
and compared against Boolean.FALSE, will never throw a NullPointerException
.
The second form, when used with the java.util.Map
interface, also, will never throw a NullPointerException
because it returns a boolean
and not a Boolean
.
If you aren't concerned about consistent coding idioms, then you can pick the one you like, and in this concrete case it really doesn't matter. If you do care about consistent coding, then consider what you want to do when you check a Boolean
that may be NULL
.
No. I don't see any advantage. Second one is more straitforward.
btw: Second style is found in every corners of JDK source.
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)
.
- Here its more about the coding style
than being the functionality....
- The 1st option is very clear, but then the 2nd one is quite elegant... no offense, its just my view..
Note: With ConcurrentMap you can use the more efficient
values.putIfAbsent(NoteColumns.CREATED_DATE, now);
I prefer the less verbose solution and avoid methods like IsTrue or IsFalse or their like.
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.
Source: Stackoverflow.com