开发者

What is better java syntax: if (isSomething() == false) { or if (!isSomething()) { [closed]

Closed. This question is opinion-based. It is not currently accepting answers.

Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.

Closed 7 years ago.

Improve this question

If you look at

if (!x) {
if (x == false) {

It looks like !x is better, but

if (!isSomething()) {
if (isSome开发者_运维问答thing() == false) {

you can easily oversee the !

What to do? Is there a recommendation?


The hidden third option is to name your variables and methods properly.

Instead of

if (!isDisabled()) {
    ...
}

use

if (isEnabled()) {
    ...
}

or if you want to check for the negative:

boolean disabled = !isEnabled();
if (disabled) {
    ...
}

or add both methods:

boolean isDisabled() {
    return !isEnabled();
}

Edit: I found this question: Is it bad to explicitly compare against boolean constants e.g. if (b == false) in Java?


I would stick with the notation if (!isSomething()) {. If you or others find it hard to read you can always add a little whitespace around the '!' in order to make it stand out:

if ( ! isSomething()) { or if ( !isSomething()) {

Furthermore, multiple conditional statements can become overwhelming with the following notation

if (isSomething() == false && isSomethingElse() == false && ..),

whereas its alternative is short and succinct. After a while it becomes natural to read the '!' along with the statements as "not isSomething() and not isSomethingElse()".


I don't think there is any recommendation that everyone would follow.

Do it your way, personnally, I would choose the if (!isSomething()) style :)

Especially since I already chose the if (!x) style.


if ( !isSomething() ) {

would be the best in my opinion. This way you're keeping the character count down, your code is readable and that ! does stick out at the beginning, so just by skimming through code, others can see its intention.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜