Java 'if' 条件中的布尔检查

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4282708/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 15:21:07  来源:igfitidea点击:

Boolean checking in the 'if' condition

javacoding-style

提问by jasonfungsing

Which one is better Java coding style?

哪一种是更好的 Java 编码风格?

boolean status = true;
if (!status) {
    //do sth
} else {
    //do sth
}

or:

或者:

if (status == false) {
    //do sth
} else {
    //do sth
}

采纳答案by missingfaktor

Former, of course. Latter is redundant, and only goes to show that you haven't understood the concept of booleans very well.

当然是前者。后者是多余的,只能表明您还没有很好地理解布尔值的概念。

One more suggestion: Choose a different name for your booleanvariable. As per this Java style guide:

还有一个建议:为boolean变量选择一个不同的名称。根据这个 Java 风格指南

is prefix should be used for boolean variables and methods.

isSet, isVisible, isFinished, isFound, isOpen

This is the naming convention for booleanmethods and variables used by Sun for the Java core packages.

Using the isprefix solves a common problem of choosing bad boolean names like statusor flag. isStatusor isFlagsimply doesn't fit, and the programmer is forced to chose more meaningful names.

Setter methods for booleanvariables must have set prefix as in:

void setFound(boolean isFound);

There are a few alternatives to the isprefix that fits better in some situations. These are has, canand shouldprefixes:

boolean hasLicense();
boolean canEvaluate();
boolean shouldAbort = false;

is 前缀应该用于布尔变量和方法。

isSet, isVisible, isFinished, isFound,isOpen

这是booleanSun 为 Java 核心包使用的方法和变量的命名约定 。

使用is前缀解决了选择错误布尔名称(如statusor )的常见问题flagisStatus或者 isFlag根本不适合,程序员被迫选择更有意义的名称。

boolean变量的Setter 方法必须设置前缀,如下所示:

void setFound(boolean isFound);

is在某些情况下,前缀有一些替代方案 更适合。这些是has,canshould前缀:

boolean hasLicense();
boolean canEvaluate();
boolean shouldAbort = false;

回答by user207421

The former. The latter merely adds verbosity.

前者。后者只是增加了冗长。

回答by Singleton

This is more readable and good practice too.

这也更具可读性和良好的实践。

if(!status){
//do sth
}else{
//do sth
}

回答by lijie

The first one, or if (status) { /*second clause*/ } else { /* first clause */ }

第一个,或 if (status) { /*second clause*/ } else { /* first clause */ }

EDIT

编辑

If the second form is really desired, then if (false == status) <etc>, while uglier, is probably safer (wrt typos).

如果确实需要第二种形式,那么if (false == status) <etc>虽然更丑陋,但可能更安全(拼写错误)。

回答by akf

I would suggest that you do:

我建议你这样做:

if (status) {
    //positive work
} else {
    // negative work
}

The ==tests, while obviously redundant, also run the risk of a single =typo which would result in an assignment.

这些==测试虽然显然是多余的,但也存在=可能导致分配的单一错字的风险。

回答by Nico Huysamen

The first one. But just another point, the following would also make your code more readable:

第一个。但还有一点,以下内容也会使您的代码更具可读性:

if (!status) {
    // do false logic
} else {
    // do true logic
}

Note that there are extra spaces between ifand the (, and also before the elsestatement.

请注意, 和之间if以及语句(之前有额外的空格else

EDIT

编辑

As noted by @Mudassir, if there is NOother shared code in the method using the logic, then the better style would be:

正如@Mudassir 所指出的,如果使用该逻辑的方法中没有其他共享代码,那么更好的样式是:

if (!status) {
    // do false logic
}

// do true logic

回答by dj_segfault

If you look at the alternatives on this page, of course the first option looks better and the second one is just more verbose. But if you are looking through a large class that someone else wrote, that verbosity can make the difference between realizing right away what the conditional is testing or not.

如果您查看此页面上的替代方案,当然第一个选项看起来更好,而第二个选项更冗长。但是,如果您正在查看其他人编写的大类,那么冗长可能会在立即意识到条件测试与否之间产生差异。

One of the reasons I moved away from Perl is because it relies so heavily on punctuation, which is much slower to interpret while reading.

我放弃 Perl 的原因之一是因为它非常依赖标点符号,在阅读时解释标点符号要慢得多。

I know I'm outvoted here, but I will almost always side with more explicit code so others can read it more accurately. Then again, I would never use a boolean variable called "status" either. Maybe isSuccess or just success, but "status" being true or false does not mean anything to the casual reader intuitively. As you can tell, I'm very into code readability because I read so much code others have written.

我知道我在这里被否决了,但我几乎总是支持更明确的代码,以便其他人可以更准确地阅读它。再说一次,我也永远不会使用名为“status”的布尔变量。也许 isSuccess 或只是成功,但“状态”是真还是假对于不经意的读者凭直觉没有任何意义。如您所知,我非常关注代码可读性,因为我阅读了很多其他人编写的代码。

回答by Petro Semeniuk

First style is better. Though you should use better variable name

第一种风格更好。虽然你应该使用更好的变量名

回答by RAY

It really also depends on how you name your variable.

这实际上还取决于您如何命名变量。

When people are asking "which is better practice" - this implicitly implies that both are correct, so it's just a matter of which is easier to read and maintain.

当人们问“哪个是更好的实践”时 - 这暗示着两者都是正确的,所以这只是一个更容易阅读和维护的问题。

If you name your variable "status" (which is the case in your example code), I would much prefer to see

如果您将变量命名为“状态”(在您的示例代码中就是这种情况),我更希望看到

if(status == false) // if status is false

if(status == false) // if status is false

On the other hand, if you had named your variable isXXX (e.g. isReadableCode), then the former is more readable. consider:

另一方面,如果您将变量命名为 isXXX(例如 isReadableCode),则前者更具可读性。考虑:

if(!isReadable) { // if not readable
  System.out.println("I'm having a headache reading your code");
}

回答by asela38

My personal feeling when it comes to reading

个人阅读的感受

if(!status) : if not status

if(status == false) : if status is false

if you are not used to !status reading. I see no harm doing as the second way.

如果您不习惯 !status 阅读。我认为第二种方法没有什么坏处。

if you use "active" instead of status I thing if(!active) is more readable

如果您使用“活动”而不是状态,我认为 if(!active) 更具可读性