Java 使用 xor 运算符进行布尔检查是一种好习惯吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/160697/
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-11 09:54:32  来源:igfitidea点击:

Is it good practice to use the xor operator for boolean checks?

javaconditionalbitwise-operatorslogical-operatorsxor

提问by Peter

I personally like the exclusive or, ^, operator when it makes sense in the context of boolean checks because of its conciseness. I much prefer to write

我个人喜欢独占或, ^, 运算符,因为它在布尔检查的上下文中有意义,因为它的简洁性。我更喜欢写作

if (boolean1 ^ boolean2)
{
  //do it
}

than

if((boolean1 && !boolean2) || (boolean2 && !boolean1))
{
  //do it
}

but I often get confused looks from other experienced Java developers (not just the newbies), and sometimes comments about how it should only be used for bitwise operations.

但我经常从其他有经验的 Java 开发人员(不仅仅是新手)那里得到困惑,有时会评论它应该如何只用于按位运算。

I'm curious as to the best practices regarding the usage of the ^operator.

我很好奇关于^操作符使用的最佳实践。

采纳答案by Peter

You can simply use !=instead.

您可以简单地使用!=

回答by Dre

I think it'd be okay if you commented it, e.g. // ^ == XOR.

我认为如果你评论它就可以了,例如// ^ == XOR

回答by Alan

If the usage pattern justifies it, why not? While your team doesn't recognize the operator right away, with time they could. Humans learn new words all the time. Why not in programming?

如果使用模式证明它是合理的,为什么不呢?虽然您的团队无法立即认出接线员,但随着时间的推移,他们可以。人类一直在学习新单词。为什么不在编程中?

The only caution I might state is that "^" doesn't have the short circuit semantics of your second boolean check. If you really need the short circuit semantics, then a static util method works too.

我可能要声明的唯一警告是“^”没有第二次布尔检查的短路语义。如果您确实需要短路语义,那么静态 util 方法也可以。

public static boolean xor(boolean a, boolean b) {
    return (a && !b) || (b && !a);
}

回答by Martin

I think you've answered your own question - if you get strange looks from people, it's probably safer to go with the more explicit option.

我想你已经回答了你自己的问题——如果你从人们那里得到奇怪的眼神,那么选择更明确的选项可能更安全。

If you need to comment it, then you're probably better off replacing it with the more verbose version and not making people ask the question in the first place.

如果你需要评论它,那么你最好用更详细的版本替换它,而不是让人们首先提出这个问题。

回答by Ates Goral

I recently used an xor in a JavaScript project at work and ended up adding 7 lines of commentsto explain what was going on. The justification for using xor in that context was that one of the terms (term1in the example below) could take on not two but three values: undefined, trueor falsewhile the other (term2) could be trueor false. I would have had to add an additional check for the undefinedcases but with xor, the following was sufficient since the xor forces the first term to be first evaluated as a Boolean, letting undefinedget treated as false:

我最近在工作中的一个 JavaScript 项目中使用了一个异或,最后添加了 7 行注释来解释发生了什么。在这种情况下使用 xor 的理由是,其中一个术语(term1在下面的示例中)可以不是两个而是三个值:undefined,true或者false另一个 ( term2) 可以是truefalse。我不得不为这些undefined情况添加一个额外的检查,但是对于 xor,以下就足够了,因为 xor 强制第一个术语首先被评估为布尔值,让我们undefined将其视为false

if (term1 ^ term2) { ...

It was, in the end, a bit of an overkill, but I wanted to keep it in there anyway, as sort of an easter egg.

最后,这有点矫枉过正,但无论如何我想把它放在那里,就像一个复活节彩蛋。

回答by Dave Tarkowski

I find that I have similar conversations a lot. On the one hand, you have a compact, efficient method of achieving your goal. On the other hand, you have something that the rest of your team might not understand, making it hard to maintain in the future.

我发现我有很多类似的对话。一方面,您有一种紧凑、有效的方法来实现您的目标。另一方面,你有一些团队其他成员可能不理解的东西,这使得将来很难维护。

My general rule is to ask if the technique being used is something that it is reasonable to expect programmers in general to know. In this case, I think that it is reasonable to expect programmers to know how to use boolean operators, so using xor in an if statement is okay.

我的一般规则是询问所使用的技术是否可以合理地期望程序员知道。在这种情况下,我认为期望程序员知道如何使用布尔运算符是合理的,因此在 if 语句中使用 xor 是可以的。

As an example of something that wouldn't be okay, take the trick of using xor to swap two variables without using a temporary variable. That is a trick that I wouldn't expect everybody to be familiar with, so it wouldn't pass code review.

举个不合适的例子,使用 xor 来交换两个变量而不使用临时变量的技巧。这是一个我不希望每个人都熟悉的技巧,因此它不会通过代码。

回答by Dave Tarkowski

!= is OK to compare two variables. It doesn't work, though, with multiple comparisons.

!= 可以比较两个变量。但是,通过多重比较它不起作用。

回答by Y--

if((boolean1 && !boolean2) || (boolean2 && !boolean1)) 
{ 
  //do it 
} 

IMHO this code could be simplified:

恕我直言,此代码可以简化:

if(boolean1 != boolean2) 
{ 
  //do it 
} 

回答by Chris Rea

str.contains("!=") ^ str.startsWith("not(")

looks better for me than

对我来说看起来比

str.contains("!=") != str.startsWith("not(")

回答by Nick

As a bitwise operator, xor is much faster than any other means to replace it. So for performance critical and scalable calculations, xor is imperative.

作为按位运算符,xor 比任何其他替代方法都要快得多。因此,对于性能关键和可扩展的计算,xor 是必不可少的。

My subjective personal opinion: It is absolutely forbidden, for any purpose, to use equality (== or !=) for booleans. Using it shows lack of basic programming ethics and fundamentals. Anyone who gives you confused looks over ^ should be sent back to the basics of boolean algebra (I was tempted to write "to the rivers of belief" here :) ).

我的主观个人意见:绝对禁止出于任何目的对布尔值使用相等(== 或 !=)。使用它表明缺乏基本的编程伦理和基础。任何让你困惑的 ^ 都应该被送回布尔代数的基础知识(我很想在这里写“信仰之河”:))。