我应该使用`!IsGood`还是`IsGood == false`?
我不断看到代码进行这样的检查,
if (IsGood == false)
{
DoSomething();
}
我
if (IsGood == true)
{
DoSomething();
}
讨厌这种语法,并且始终使用以下语法。
if (IsGood)
{
DoSomething();
}
或者
if (!IsGood)
{
DoSomething();
}
是否有任何理由使用“== true
”或“== false
”?
这是一个可读性的问题吗? 人们只是不理解布尔变量吗?
另外,两者之间有性能差异吗?
I keep seeing code that does checks like this
if (IsGood == false)
{
DoSomething();
}
or this
if (IsGood == true)
{
DoSomething();
}
I hate this syntax, and always use the following syntax.
if (IsGood)
{
DoSomething();
}
or
if (!IsGood)
{
DoSomething();
}
Is there any reason to use '== true
' or '== false
'?
Is it a readability thing? Do people just not understand Boolean variables?
Also, is there any performance difference between the two?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(30)
我遵循与您相同的语法,它不那么冗长。
人们(更多的初学者)更喜欢使用
== true
只是为了确保这是他们想要的。 他们习惯于在条件中使用运算符...他们发现它更具可读性。 但一旦你变得更高级,你就会发现它很烦人,因为它太冗长了。I follow the same syntax as you, it's less verbose.
People (more beginner) prefer to use
== true
just to be sure that it's what they want. They are used to use operator in their conditional... they found it more readable. But once you got more advanced, you found it irritating because it's too verbose.当我遇到时,我总是咯咯地笑(或者向某人扔东西,这取决于我的心情),
因为如果你不能依赖比较返回布尔值的事实,那么你也不能依赖将结果与 true 进行比较,所以代码应该变成
但是,当然,这真的应该是
但是,当然......
(啊,编译失败。回去工作。)
I always chuckle (or throw something at someone, depending on my mood) when I come across
because surely if you can't rely on the fact that your comparison returns a boolean, then you can't rely on comparing the result to true either, so the code should become
but, of course, this should really be
but, of course ...
(ah, compilation failed. Back to work.)
我更喜欢更短的变体。 但有时
== false
有助于使代码更短:对于使用 C# 2.0 的项目中的现实场景,我认为这样做只有一个很好的理由:
bool?
类型。 三态bool?
很有用,并且可以通过这种方式轻松检查其可能值之一。实际上,如果
IsGood
是bool?
,则不能使用(!IsGood)
。 但是编写(IsGood.HasValue && IsGood.Value)
比(IsGood == true)
更糟糕。玩一下这个示例来了解一下:
我刚刚发现了另一种情况,其中
if (!IsGood) { ... }
与if (IsGood == false ) { ... }
。 但这是不现实的;) 运算符重载可能会有所帮助:) (并且运算符 true/false AFAIK 在 C# 2.0 中不鼓励使用,因为它的预期目的是为用户定义类型提供类似于 bool? 的行为,现在你可以用标准类型得到它!)所以...请谨慎使用运算符重载:(
I would prefer shorter variant. But sometimes
== false
helps to make your code even shorter:For real-life scenario in projects using C# 2.0 I see only one good reason to do this:
bool?
type. Three-statebool?
is useful and it is easy to check one of its possible values this way.Actually you can't use
(!IsGood)
ifIsGood
isbool?
. But writing(IsGood.HasValue && IsGood.Value)
is worse than(IsGood == true)
.Play with this sample to get idea:
There is one more case I've just discovered where
if (!IsGood) { ... }
is not the same asif (IsGood == false) { ... }
. But this one is not realistic ;) Operator overloading may kind of help here :) (and operator true/false that AFAIK is discouraged in C# 2.0 because it is intended purpose is to provide bool?-like behavior for user-defined type and now you can get it with standard type!)So... please, use operator overloading with caution :(
根据Code Complete一本书Jeff 的名字来自 并高度评价以下是对待布尔值的方式。
我过去常常实际比较布尔值,但我想为什么要在该过程中添加额外的步骤并将布尔值视为二流类型。 在我看来,比较返回一个布尔值,并且布尔类型已经是布尔值,所以为什么不只使用布尔值。
真正的争论归根结底是为你的布尔值使用好名字。 就像你上面所做的那样,我总是在问题的 for 中表达我的布尔对象。 如
According to Code Complete a book Jeff got his name from and holds in high regards the following is the way you should treat booleans.
I use to go with actually comparing the booleans, but I figured why add an extra step to the process and treat booleans as second rate types. In my view a comparison returns a boolean and a boolean type is already a boolean so why no just use the boolean.
Really what the debate comes down to is using good names for your booleans. Like you did above I always phrase my boolean objects in the for of a question. Such as
如果所讨论的变量确实应该用作布尔值(即使其类型不是布尔值),那么专门针对 true 或 false 进行测试的技术绝对是不好的做法 - 特别是在 C/C++ 中。 针对
true
进行测试可能(并且可能会)导致微妙的错误:这些明显相似的测试给出相反的结果:
这将显示以下结果:
如果您觉得需要测试用作布尔标志的变量针对 true/false (我认为不应该这样做),您应该使用始终测试 false 的习惯用法,因为 false 只能有一个值 (
0
),而 true 可以有多个可能的值值(0
以外的任何值):有些人会认为这是 C/C++ 中的缺陷,这可能是真的。 但这是这些语言(可能还有许多其他语言)中的一个事实,因此我会坚持使用简短的习惯用法,即使在像 C# 这样不允许您使用整数值作为布尔值的语言中也是如此。
请参阅此问题,了解此问题实际上咬伤某人的示例...
The technique of testing specifically against true or false is definitely bad practice if the variable in question is really supposed to be used as a boolean value (even if its type is not boolean) - especially in C/C++. Testing against
true
can (and probably will) lead to subtle bugs:These apparently similar tests give opposite results:
This displays the following result:
If you feel the need to test variable that is used as a boolean flag against true/false (which shouldn't be done in my opinion), you should use the idiom of always testing against false because false can have only one value (
0
) while a true can have multiple possible values (anything other than0
):Some people will have the opinion that this is a flaw in C/C++, and that may be true. But it's a fact of life in those languages (and probably many others) so I would stick to the short idiom, even in languages like C# that do not allow you to use an integral value as a boolean.
See this SO question for an example of where this problem actually bit someone...
我同意你的观点(也对此感到恼火)。 我认为
IsGood == true
计算结果为bool
这只是一个轻微的误解,这就是IsGood
的开始。我经常看到
SomeStringObject.ToString()
的这些邻近实例。也就是说,在类型处理比较宽松的语言中,这可能是合理的。 但在 C# 中则不然。
I agree with you (and am also annoyed by it). I think it's just a slight misunderstanding that
IsGood == true
evaluates tobool
, which is whatIsGood
was to begin with.I often see these near instances of
SomeStringObject.ToString()
.That said, in languages that play looser with types, this might be justified. But not in C#.
有些人发现针对已知值的显式检查更具可读性,因为您可以通过读取来推断变量类型。 我不知道一个是否比另一个更好。 他们都工作。 我发现,如果变量本质上持有“逆”,那么我似乎倾向于检查一个值:
或者
而不是
但是,这对我来说并不重要,而且我确信它最终会成为相同的 IL 。
Some people find the explicit check against a known value to be more readable, as you can infer the variable type by reading. I'm agnostic as to whether one is better that the other. They both work. I find that if the variable inherently holds an "inverse" then I seem to gravitate toward checking against a value:
or
instead of
But again, It doen't matter much to me, and I'm sure it ends up as the same IL.
仅可读性......
如果您喜欢的方式在编译成机器代码时更有效。 但是我希望它们生成完全相同相同的机器代码。
Readability only..
If anything the way you prefer is more efficient when compiled into machine code. However I expect they produce exactly the same machine code.
从到目前为止的答案来看,这似乎是共识:
From the answers so far, this seems to be the consensus:
我更喜欢使用:
并且
我发现这更具可读性 - ! 太容易错过(无论是阅读还是打字); 还有“if not IsGood then...”,当我听到它时听起来不太正确,而不是“if IsGood is false then...”,后者听起来更好。
I prefer to use:
and
as I find this more readable - the ! is just too easy to miss (in both reading and typing); also "if not IsGood then..." just doesn't sound right when I hear it, as opposed to "if IsGood is false then...", which sounds better.
有可能(虽然不太可能,但至少我希望)在 C 代码中 TRUE 和 FALSE 被 #define 为 1 和 0 以外的东西。例如,程序员可能决定使用 0 作为“true”,使用 -1 作为“false” “在特定的 API 中。 对于遗留的 C++ 代码也是如此,因为“true”和“false”并不总是 C++ 关键字,特别是在 ANSI 标准出现之前。
还值得指出的是,某些语言(尤其是 Perl、JavaScript 和 PHP 等脚本语言)可以对哪些值算作 true 和哪些值算作 false 有有趣的解释。 “foo == false”的含义可能与“!foo”略有不同(尽管再次强调,希望不大)。 这个问题被标记为“与语言无关”,并且语言可以将 == 运算符定义为不以与 ! 兼容的方式工作。 操作员。
It's possible (although unlikely, at least I hope) that in C code TRUE and FALSE are #defined to things other than 1 and 0. For example, a programmer might have decided to use 0 as "true" and -1 as "false" in a particular API. The same is true of legacy C++ code, since "true" and "false" were not always C++ keywords, particularly back in the day before there was an ANSI standard.
It's also worth pointing out that some languages--particularly script-y ones like Perl, JavaScript, and PHP--can have funny interpretations of what values count as true and what values count as false. It's possible (although, again, unlikely on hopes) that "foo == false" means something subtly different from "!foo". This question is tagged "language agnostic", and a language can define the == operator to not work in ways compatible with the ! operator.
我将以下内容视为 C/C++ 风格要求。
原因是,如果您不小心将“=”而不是“==”,编译器将放弃为常量赋值。 与此同时,它会损害每个 if 语句的可读性。
I've seen the following as a C/C++ style requirement.
The reasoning was if you accidentally put "=" instead of "==", the compiler will bail on assigning a value to a constant. In the meantime it hurts the readability of every single if statement.
有时它在可读性方面有用途。 有时,命名变量或函数调用最终可能会成为双重否定,这可能会令人困惑,而像这样明确预期的测试可以提高可读性。
一个很好的例子是 strcmp() C/C++,如果字符串相等则返回 0,否则 << 或> 0,取决于差异在哪里。 所以你会经常看到:
一般来说,但我会同意你的观点,这样
读起来更清晰。
Occasionally it has uses in terms of readability. Sometimes a named variable or function call can end up being a double-negative which can be confusing, and making the expected test explicit like this can aid readability.
A good example of this might be strcmp() C/C++ which returns 0 if strings are equal, otherwise < or > 0, depending on where the difference is. So you will often see:
Generally however I'd agree with you that
is clearer to read.
我更喜欢 !IsGood 方法,而且我认为大多数具有 C 风格语言背景的人也会更喜欢它。 我只是在这里猜测,但我认为大多数编写 IsGood == False 的人都来自更详细的语言背景,例如 Visual Basic。
I prefer the !IsGood approach, and I think most people coming from a c-style language background will prefer it as well. I'm only guessing here, but I think that most people that write IsGood == False come from a more verbose language background like Visual Basic.
唯一更糟糕的是
从来没有理解该方法背后的想法。
Only thing worse is
Never understood the thought behind that method.
当简化为正则表达式时,
!IsGood
模式比IsGood == false
更容易找到。与
The
!IsGood
pattern is eaiser to find thanIsGood == false
when reduced to a regular expression.vs
为了便于阅读,您可以考虑一个依赖于另一个属性的属性:
然后,您可以真正理解其含义:
For readability, you might consider a property that relies on the other property:
Then, you can really get across the meaning:
我更喜欢
!IsGood
因为对我来说,它更加清晰和简洁。 检查 boolean == true 是否是多余的,所以我会避免这样做。 但从语法上来说,我认为检查IsGood == false
没有区别。I prefer
!IsGood
because to me, it is more clear and consise. Checking if aboolean == true
is redundant though, so I would avoid that. Syntactically though, I don't think there is a difference checking ifIsGood == false
.在许多语言中,区别在于,在一种情况下,编译器/解释器决定 true 或 false 的含义,而在另一种情况下,它是由代码定义的。 C 就是一个很好的例子。
在上面的示例中,“something”与编译器的“true”定义进行了比较。 通常这意味着“不为零”。
在上面的例子中,“某事”与“真实”进行了比较。 “true”的类型(以及因此的可比性)和“true”的值可能由语言和/或编译器/解释器定义,也可能不由语言和/或编译器/解释器定义。
通常两者并不相同。
In many languages, the difference is that in one case, you are having the compiler/interpreter dictate the meaning of true or false, while in the other case, it is being defined by the code. C is a good example of this.
In the above example, "something" is compared to the compiler's definition of "true." Usually this means "not zero."
In the above example, "something" is compared to "true." Both the type of "true" (and therefor the comparability) and the value of "true" may or may not be defined by the language and/or the compiler/interpreter.
Often the two are not the same.
你忘了:
You forgot:
在我看来(尽管我没有证据支持这一点),从 C#/java 类型语言开始的人更喜欢“if (CheckSomething())”方法,而从其他语言(C++:特别是 Win32)开始的人C++)出于习惯倾向于使用其他方法:在 Win32 中,如果 CheckSomething 返回 BOOL(而不是 bool),“if (CheckSomething())”将不起作用; 在许多情况下,API 函数显式返回 0/1 int/INT,而不是 true/false 值(这就是 BOOL)。
出于习惯,我总是使用更详细的方法。 它们在语法上是相同的; 我不相信“冗长让我恼火”的废话,因为程序员不是需要被代码打动的人(计算机需要)。 而且,在现实世界中,任何查看我编写的代码的人的技能水平都会有所不同,并且我没有时间或意愿向可能不了解一些不重要的事情的人解释语句评估的特殊性。像那样的位。
It seems to me (though I have no proof to back this up) that people who start out in C#/java type languages prefer the "if (CheckSomething())" method, while people who start in other languages (C++: specifically Win32 C++) tend to use the other method out of habit: in Win32 "if (CheckSomething())" won't work if CheckSomething returns a BOOL (instead of a bool); and in many cases, API functions explicitly return a 0/1 int/INT rather than a true/false value (which is what a BOOL is).
I've always used the more verbose method, again, out of habit. They're syntactically the same; I don't buy the "verbosity irritates me" nonsense, because the programmer is not the one that needs to be impressed by the code (the computer does). And, in the real world, the skill level of any given person looking at the code I've written will vary, and I don't have the time or inclination to explain the peculiarities of statement evaluation to someone who may not understand little unimportant bits like that.
啊,我有一些同事喜欢较长的形式,认为它比小形式更具可读性!
我开始“修复”这个问题,因为布尔值是自给自足的,所以我放弃了十字军东征... ^_^ 他们不喜欢在这里清理代码,无论如何,他们认为这使得分支之间的集成变得困难(这是事实,但是那么你就永远带着难看的代码生活......)。
如果你正确地书写了布尔变量名,它应该自然地读起来:
if (isSuccessful)
与if (returnCode)
在某些情况下我可能会沉迷于布尔比较,例如:
if (PropertyProvider.getBooleanProperty(SOME_SETTING, true) == true)
因为它读起来不太“自然”。Ah, I have some co-worked favoring the longer form, arguing it is more readable than the tiny !
I started to "fix" that, since booleans are self sufficient, then I dropped the crusade... ^_^ They don't like clean up of code here, anyway, arguing it makes integration between branches difficult (that's true, but then you live forever with bad looking code...).
If you write correctly your boolean variable name, it should read naturally:
if (isSuccessful)
vs.if (returnCode)
I might indulge in boolean comparison in some cases, like:
if (PropertyProvider.getBooleanProperty(SOME_SETTING, true) == true)
because it reads less "naturally".出于某种原因,我总是喜欢
超过
,这就是为什么我有点喜欢 Ruby 的 except(但它有点太容易滥用):
如果像这样使用,甚至更多:
For some reason I've always liked
more than
and that's why I kind of like Ruby's unless (but it's a little too easy to abuse):
and even more if used like this:
Cybis,在使用 C++ 进行编码时,您还可以使用 not 关键字。 它是很久以前的标准的一部分,所以这段代码是完全有效的:
编辑:顺便说一句,我忘了提及该标准还定义了其他布尔关键字,例如 和 (&&), 位与 (&)、或 (||)、位或 (|)、异或 (^)。 ..它们被称为运算符同义词。
Cybis, when coding in C++ you can also use the not keyword. It's part of the standard since long time ago, so this code is perfectly valid:
Edit: BTW, I forgot to mention that the standard also defines other boolean keywords such as and (&&), bitand (&), or (||), bitor (|), xor (^)... They are called operator synonyms.
如果您确实认为需要:
那么由于条件表达式本身就是布尔值,您可能希望将其扩展为:
等等。 这口棺材还需要多少颗钉子?
If you really think you need:
then since the conditional expression is itself boolean you probably want to expand it to:
and so on. How many more nails does this coffin need?
如果你碰巧在 perl 中工作,你可以选择
If you happen to be working in perl you have the option of
我不使用
==
但有时我使用!=
因为它在我的脑海中更清晰。 但在我的工作中,我们不使用!=
或==
。 我们尝试使用hasXYZ()
或isABC()
获取有意义的名称。I do not use
==
but sometime I use!=
because it's more clear in my mind. BUT at my job we do not use!=
or==
. We try to get a name that is significat if withhasXYZ()
orisABC()
.就我个人而言,我更喜欢鲍勃叔叔在《干净的代码》中谈论的形式:
其中条件语句(除了最琐碎的条件之外)都放在谓词函数中。 那么布尔表达式的实现的可读性就不那么重要了。
Personally, I prefer the form that Uncle Bob talks about in Clean Code:
where conditionals, except the most trivial ones, are put in predicate functions. Then it matters less how readable the implementation of the boolean expression is.
我们倾向于在这里执行以下操作:
或者
这样做的原因是因为我们有一些由不再在这里(在 Delphi 中)的人编写的遗留代码,看起来像:
这在过去给我们带来了很多痛苦,所以我们决定始终尝试检查阳性结果; 如果不可能,则将负数与假数进行比较。
We tend to do the following here:
or
The reason for this is because we've got some legacy code written by a guy that is no longer here (in Delphi) that looks like:
This has caused us much pain in the past, so it was decided that we would always try to check for the positive; if that wasn't possible, then compare the negative to false.
我唯一一次能想到更冗长的代码有意义的是在 .NET Visual Basic 之前的版本中,其中 true 和 false 实际上是整数(true=-1,false=0),而布尔表达式如果计算为零且被认为是 false,对于任何其他非零值均为 true。 因此,在旧版 VB 中,列出的两种方法实际上并不等效,如果您只想在计算结果为 -1 时为 true,则必须显式地与“true”进行比较。 因此,如果计算结果为整数(因为它不为零),则计算结果为“+1”的表达式将为 true,但它不等于“true”。 我不知道为什么 VB 是这样设计的,但我在旧的 VB 代码中看到很多布尔表达式将变量与 true 和 false 进行比较。
The only time I can think where the more vebose code made sense was in pre-.NET Visual Basic where true and false were actually integers (true=-1, false=0) and boolean expressions were considered false if they evaluated to zero and true for any other nonzero values. So, in the case of old VB, the two methods listed were not actually equivalent and if you only wanted something to be true if it evaluated to -1, you had to explicitly compare to 'true'. So, an expression that evaluates to "+1" would be true if evaluated as integer (because it is not zero) but it would not be equivalent to 'true'. I don't know why VB was designed that way, but I see a lot of boolean expressions comparing variables to true and false in old VB code.