if (boolean == false) vs. if (!boolean) [duplicate]

空扰寡人 提交于 2019-11-28 22:51:18

问题


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?


回答1:


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.)




回答2:


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.




回答3:


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).




回答4:


- 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..




回答5:


No. I don't see any advantage. Second one is more straitforward.

btw: Second style is found in every corners of JDK source.




回答6:


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.




回答7:


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.



来源:https://stackoverflow.com/questions/11831881/if-boolean-false-vs-if-boolean

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!