简体   繁体   English

我应该避免在Java中的if语句中使用“!”吗?

[英]Should I avoid using “!” in if statement in Java?

Our team's Java Coding Guideline says: 我们团队的Java编码指南说:

Avoid using "!" 避免使用“!” in if statement as much as possible. 在if语句中尽可能多。

I have asked other colleagues, but no one gave me clear ideas why, because the guideline was created a long time ago and the author might have left our company. 我问其他同事,但没有人给我清楚的想法,因为该指南是很久以前创建的,作者可能已离开我们公司。

Do you have any idea? 你有什么主意吗?

With the information provided, this calls for some speculation. 根据提供的信息,这需要一些推测。 One possible reason is that the intent was not for an if-statement by itself but for an if-else statement. 一个可能的原因是,意图本身不是if语句,而是if-else语句。 In that case, I can see where you might say that you should reverse the cases so that you don't have the extra operation of the negation. 在这种情况下,我可以看到你可能会说你应该反转案件,以便你没有额外的否定操作。 Instead of 代替

if (! boolVar) {
  // Something
} else {
  // Something else
}

you might prefer 你可能更喜欢

if (boolVar) {
  // Something else
} else {
  // Something
}

Whether this is worth it or not is probably more a matter of taste and standardization than anything else. 这是否值得,可能更多的是品味和标准化问题。

The rule is likely an adaptation from Robert Martin's Clean Code , page 302: 该规则很可能是罗伯特·马丁的清洁法典第302页的改编:

Negatives are just a bit harder to understand than positives. 负面消息比正面消息更难理解。 So, when possible, conditionals should be expressed as positives. 因此,在可能的情况下,条件应表示为正数。 For example: 例如:

 if(buffer.shouldCompact()) 

is preferable to 比较好

 if(!buffer.shouldNotCompact()) 

As an example, suppose you're creating a validator that requires two things to be false for the entity to be valid: 例如,假设您正在创建一个验证程序,该验证程序需要两个错误才能使实体有效:

  • The entity must not have been created within the last 12 hours, and 该实体不得在过去12小时内创建,并且
  • The entity's bank account total sum must not exceed $50,000. 该实体的银行账户总金额不得超过50,000美元。

Naturally the idea would be to write two methods for this: 当然,我们的想法是为此编写两种方法:

boolean isCreatedWithinLastTwelveHours(BankAccount account)
boolean hasMoreThanTotalSumCap(BankAccount account)

...at which point, you then invoke these as: ...然后,您将其调用为:

boolean newAccount = isCreatedWithinTheLastTwelveHours(account);
boolean highEndAccount = hasMoreThanTotalSumCap(account);

if(!newAccount && !highEndAccount) { // ... other logic

// The more astute would use DeMorgan's law in an effort to make this more readable

if(!(newAccount || highEndAccount)) { // other logic

Well...wouldn't it be nicer if you just said what they weren't instead? 嗯......那岂不是更好,如果你只是说他们不是代替呢?

boolean isNotCreatedWithinLastTwelveHours(BankAccount account)
boolean hasLessThanTotalSumCap(BankAccount account)

That'd make the expression a bit more concise: 这使得表达更加简洁:

if(notNewAccount && notHighEndAccount) { // .. carry on!

Of course "!" 当然 ”!” can be used when you like. 可以在你喜欢的时候使用。 There is no "unless" in java and you have no other choices in some conditions. java中没有“除非”,在某些情况下你没有其他选择。

Looks like yet-another-useless-rule. 看起来还是另一个无用的规则。 Generally speaking, there are no absolute terms in this scenario, true that if you are in a if-else clause then possibly it is better to write 一般来说,在这种情况下没有绝对术语,如果你在if-else子句中,那么可能最好写一下

if(myCondition) {
    doThis()
} else {
    doSomethingElse()
}

Instead of 代替

if(!myCondition) {
   doSomethingElse()
} else {
   doThis()
}

However, that said, in some scenarios is actually quite ok to use the negation operator, particularly if no else clause is provided, example 但是,在某些情况下,实际上使用否定运算符是非常好的,特别是如果没有提供else子句,例如

if (!tokenDoesCompute()) {
   throw InvalidTockenException("Whatever")
}

And actually in that scenario, using "!" 实际上在这种情况下,使用“!” makes quite a bit of sense for me. 对我来说有点意义。

Finally, if no one can really explain WHY the rule is there, maybe it is time to remove it, the only good reason I could find for it would be to provide consistency regarding the code style. 最后,如果没有人可以真正解释为什么规则存在,也许是时候删除它,我能找到它的唯一好处是提供有关代码风格的一致性。

Okay, I answer my own question. 好的,我回答了我自己的问题。 As other say, maybe this is written for the readability. 正如其他人所说,也许这是为了可读性而写的。

In The Art of Readable Code (p. 72) says: “可读代码的艺术” (第72页)中说:

Prefer dealing with the positive case first instead of the negative-eg, if(debug) instead of if(!debug) 首先处理正面情况而不是负面情况 - 例如if(debug)而不是if(!debug)

I found below post as well: 我发现下面的帖子:

Ofcourse you can use the negation operator ! 当然你可以使用否定运算符! whenever you like. 随时随地。

However, if you have a situation where you have to write some actions in both if and else block then the following is more readable : 但是,如果您遇到必须在ifelse块中编写某些操作的情况,则以下内容更具可读性:

if(status){
//do something
}
else{
//do something else
}

than

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

But if you have situation where you only need to perform certain actions based on just one condition, ie if you have only an if block & no else block, then it is reasonably fine to use ! 但是如果你有这样的情况你只需要根据一个条件执行某些操作,即如果你只有一个if块而没有else块,那么使用起来相当合理! in if if

I haven't seen anyone else suggest this, which is probably because they hate it as much as I do, but I'm showing it for completeness. 我没有看到其他人提出过这个问题,这可能是因为他们和我一样讨厌它,但我是为了完整而展示它。

// Using not operator (preferred)
if (! someTest) { ... }

// Using compact not operator (kind of hides it)
if (!someTest) { ... }

// Comparing to false (ok, explicitly states what you want)
if (someTest == false) { ... }

// Comparing to true (a bit obscure)
if (someTest != true) { ... }

They all do the same, but please keep using ! 他们都这样做,但请继续使用! , just make sure you add a space after it, so it's easier to see. ,请确保在其后添加空格,以便更容易看到。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM