if(!value) 和 if(flag == value) 哪个形式更清晰?
我知道这是一个主观问题,所以如果需要关闭它,我深表歉意,但我觉得这个问题经常出现,足以让我想知道是否存在对一种形式相对于另一种形式的普遍偏好。
显然,最好的答案是“重构代码,这样你就不需要测试是否有误”,但有时没有简单的方法可以做到这一点,“else”分支只是继续处理。因此,当您必须有一个“if not false”构造时,这是首选标准:
not 运算符
if (!value)
或 false 测试
if (value == false)
I understand this is a subjective question, so I apologize if it needs to be closed, but I feel like it comes up often enough for me to wonder if there is a general preference for one form over the other.
Obviously, the best answer is "refactor the code so you don't need to test for falsehood" but sometimes there's no easy way to do so and the "else" branch is simply to continue processing. So when you must have an "if not false" construct, which is the preferred standard:
The not operator
if (!value)
Or the test for false
if (value == false)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(19)
if (!value)
更容易/更快地遵循。正如你所说,主观。只要你保持一致,这是最重要的。编辑
另外一点要添加 - 省略 true/false 关键字也应该(希望)强制编码器使用更好的命名变量。 Bool 变量应始终指示含义或状态目的,例如:
if (MyWallet.IsEmpty)
上述内容没有理由使用
== false
或= = true
因为它是多余的。上面的内容是人类立即可读的。比必须破译:
if (MyWallet.EmptyStatus == true)
或类似这样的荒谬的东西要好得多。if (!value)
is easier/faster to follow. Subjective as you said. As long as you are consistent, this is the main thing.EDIT
One other point to add - omitting the true/false keywords should also (hopefully) force the coder to use better named variables. Bool variables should always indicate meaning or state purpose, such as:
if (MyWallet.IsEmpty)
There is no reason with the above to use
== false
or== true
as it's redundant. The above is human readable immediately.Far better than having to decipher:
if (MyWallet.EmptyStatus == true)
or something ridiculous like this.我个人喜欢
if ((value == false) == true)
...因为这是验证语句
value is false
实际上评估为布尔值 true。 ..然后,显然,涵盖这两种可能性会更加清晰,
if ((value == false) == true && (value == false) != false)
对于那些真正渴望清晰性并要求无可争议的可读性的人,我建议
if (((value == false) == true && ; (value == false) != false) == true)
但说真的,我只是想添加这个,创建适当且有意义的变量名称是这个问题的关键。您可以轻松地在声明 value 的类中添加计算变量,如下所示(例如“value”实际上是“LaunchMissile”),
public bool AbortLaunch =>; !发射导弹
,那么你所需要的就是
如果(AbortLaunch)...
,然后它很简洁,非常易读,并且避免了否定运算符。
I personally like
if ((value == false) == true)
...cause this is verifying that the statement
value is false
is actually evaluating to a boolean true...and, then, obviously, covering both posssibilites adds even more clarity,
if ((value == false) == true && (value == false) != false)
<grin/>
and for those of you who are real gluttons for clarity, and demand incontrovertible readability, I'd suggest
if (((value == false) == true && (value == false) != false) == true)
But seriously, and I just thought of adding this, creating appropriate and meaningful variable Names is the key to this issue. You can easily, in the class where value is declared, add a computed variable as in (say "value "is actually "LaunchMissile"),
public bool AbortLaunch => !LaunchMissile
,then all you need is
if (AbortLaunch) ...
,and then it is terse, eminently readable, and avoids the negation operator.
在我看来,这一点总是更清楚。
我讨厌这样说,因为这听起来有点刻薄,但这通常表明编写代码的人并不真正理解布尔值的使用。您不需要重新验证 if 语句中的布尔值是什么。这是多余的。
(就我个人而言,如果他们将变量命名为
value
而不是更有意义的东西,我也会对这个人感到恼火。我有一种感觉,你发布的只是伪代码,我肯定会在评论中指出这一点.)编辑(回应下面的评论):
它可能看起来微不足道,但通常它是更大事情的标志。说实话,大多数使用 var == true 等的人都不明白。这只是事实。我并不是说他们愚蠢或者他们不应该成为程序员,只是说他们可能需要回顾和学习一些东西。问题是,当逻辑变得更加复杂时,不理解这样的概念可能会导致更大的问题。有人说“这是一种风格”。没关系。在这种情况下,真正的问题是,“这样做对我有什么好处?我或其他人能从中得到什么?”如果你不能坚定地回答这个问题,那么你需要问自己“为什么这是一个好主意?”
This is always clearer in my opinion.
I hate to say this, because it sounds kind of mean, but this normally shows that the person writing the code doesn't really understand the use of boolean values. You don't need to re-validate what a boolean is in an if statement. It's redundant.
(Personally, I would be annoyed at the person too if they named the variable
value
instead of something more meaningful. I have a feeling what you posted is just psuedo code, I would definitely ding that on a review.)Edit (in response to a comment below):
It may look trivial, but often it is a sign of much bigger things. Truthfully, most people who do use var == true etc. don't understand. It's just a fact. I'm not saying their stupid or they shouldn't be programmers just that there is probably something that they need to review and learn. The problem is that when logic gets much more complex, not understanding concepts like this can lead to much much bigger problems down the road. Some people say "it's a style." That's fine. The real question in this case is, "How is it beneficial for me to do it this way? What do I or other people get from it?" If you can't solidly answer that question, then you need to ask yourself "Why is this a good idea?"
我永远不会使用
if(value == true)
,所以为了保持一致性,我也不会使用if(value != false)
。I would never use
if(value == true)
, so just for consistency I would also not useif(value != false)
.不同意见(某种程度上)
从编译的角度来看,您将获得相同的 IL,因此它实际上只从可读性的角度来看很重要。
从这个角度来看,
if(value == false)
对于普通读者来说更加明显,并且错过 ! 的可能性较小。在布尔之前。老实说,我使用这两种方法,而且大多数时候,我让它取决于我的变量名称。如果用“not”代替“bang”听起来仍然可以,我可能会使用 bang 符号,
例如
Dissenting opinion (kind of)
From a compilation standpoint, you're going to get the same IL, so it really only matters from a readability standpoint.
From that standpoint, the
if(value == false)
is more obvious to a casual reader, and there is less chance of missing the ! before the bool.Honestly, I use both approaches, and most times, I make it depend on my variable name. If it still sounds ok to say "not" in place of the "bang", I'm likely to use the bang notation
e.g.
if(!value)
更清晰、更“优雅”,特别是如果你正确命名布尔变量类似的东西
对我来说似乎是多余的
if(!value)
is clearer and more "elegant", specially if you name boolean variables correctlySomething like
seems redundant to me
在 VB 中编码时我使用
Not value
,但在 C# 中编码时倾向于使用value == false
。我发现感叹号有时会在变量名称中丢失(例如!legal)。也许是因为我是,呃,一个经验丰富的老手。I use
Not value
when coding in VB but tend to usevalue == false
when coding in C#. I find that the exclamation point can sometimes be lost in the name of the variable (e.g. !legal). Maybe it's because I'm, uh, a seasoned veteran.我倾向于使用 if(!value) ,因为根据所涉及变量的名称,根据英语语义,“true”情况更有意义。
请考虑这篇 MSDN 文章 中的示例之一:
英文读作“如果选中窗格”。
但是, if(
pane.IsChecked == true
) 的英文读作是“如果窗格是否被检查为 true”。该声明在英语中的表达远不如应有的清晰。我们不以二进制形式编写 C# 代码的原因之一是人类可读性。如果您需要在阅读流畅的代码和阅读流畅的代码之间做出选择,请选择更具可读性的代码。我不认为添加“
== true
”会使这个示例更具可读性,MSDN 也不这么认为。诚然,这是一个值得担心的小例子。但正如其他一些答案所表明的那样,不将这种思维方式应用于更大规模的案例可能会损害可读性。
I would favor using
if(!value)
because, depending on the names of the variables involved, the "true" case makes much more sense according to English semantics.Consider one of the examples in this MSDN article:
reads in English as, "If the pane is checked".
However, if(
pane.IsChecked == true
) reads in English as "If whether the pane is checked is true". That statement that is far less clear in English than it should be.One of the reasons why we don't write C# code in binary is human readability. If you're given the choice between code that flows well when you read it and code that doesn't, side with the one that is more readable. I don't think adding the "
== true
" makes this example more readable, and MSDN doesn't think so either.Granted, this is a rather small example to worry about. But as some of the other answers have indicated, not applying this way of thinking to larger-scale cases can hurt readability.
当我确定 value 是一个布尔值时,我通常也更喜欢 if (!value) 。但很多时候它可以是字符串,也可以是数字。
在许多语言(但不是全部)的条件语句中,数字零将计算为假;但是,字符串“0”的计算结果为true。这是一个问题,特别是在 JavaScript 中,特别是如果您从服务器接收 JSON 字符串,特别是如果服务器是用 PHP 编写的(因为大多数 PHP 开发人员都很粗心,只是从数据库中获取值并对其调用 json_encode,而不知道数据库产生字符串,并且不知道它们用作布尔字段的所有这些零和一将在另一端编码为字符串,因此全部被视为true在条件句中)。
咆哮完了。我的建议:要明确,特别是如果您的语言是“非常动态”的类型(即 JavaScript、PHP、Perl)。
I would normally prefer if (!value) too, when I know for sure that value is a boolean. But many times it can be a string, or a number.
The number zero would evaluate to false in conditionals in a lot of languages (not all, though); however, the string "0" would evaluate to true. This is a problem particularly in JavaScript, particularly if you receive JSON strings from the server, particularly if the server is written in PHP (because most PHP developers are careless enough to just take values from the DB and call json_encode on them, not knowing that the DB yields strings and not having a clue that all those zeros and ones that they use as boolean fields will be encoded as strings on the other end, thus all treated as true in conditionals).
Rant over. My suggestion: be explicit, especially if your language is the “very dynamic” type (i.e. JavaScript, PHP, Perl).
无论你喜欢哪一种。选择一个并坚持下去。
Whatever one you prefer. Pick one and stick to it.
我很遗憾地说,第二个对我来说看起来很愚蠢。
如果有人喜欢的话,我会添加一个额外的级别:
:)
I am sorry to say, the second just looks stupid to me.
I'd add an extra level, if someone prefers it:
:)
我不认为这有那么主观。我从未看到它以较长的形式被推荐。实际上,我读过的所有书籍和编码指南以及“如何成为一名优秀的程序员”HowTos 都不鼓励这样做。
它与 OTOH 属于同一类别
,这里给出的所有答案使我的第一个陈述有点不真实。
I don't think it's all that subjective. I have never seen it recommended in the longer form. Actually all the books and coding guides and "How to be a good programmer" HowTos I've read discourage it.
It falls in the same category as
OTOH, all the answers given here make my first statement kinda equal not true.
我至少喜欢使用
if (!value)
样式来评估变量或常见属性,例如Page.IsPostback
等。对于任何更复杂的事情,我倾向于将表达式括起来,如下所示:只是为了引起更多关注。
总而言之,它是 Perl 风格的
unless
和until
关键字的参数。I favour the
if (!value)
style at least for evaluating variables or common properties likePage.IsPostback
and the like. For anything more complex I tend to parenthesise the expression like thus:Just to draw a little more attention to it.
All in all, it's an argument for Perl-style
unless
anduntil
keywords.如果条件只是检查单个值,那么
!value
会更快。但是,当条件包含多个值检查时,我发现读取
value == false
更容易。不知何故,解析多个相等性检查比解析多个值否定更容易。If the condition is just a check of a single value, then
!value
is quicker.However, when the condition contains multiple value checks, I find it much easier to read
value == false
. Somehow it is easier to parse multiple checks for equality than multiple negations of values.我其实有很多种可能的形式。
这实际上并不是按照标准编写的,但这就是我的看法:
因此我不认为 == false 是多余的。
I actually many of forms possible.
This is not actually how it is written to standards, but this is how I see it:
Hence I don’t see == false is redundant.
我更喜欢第二个选项,即
if (value == false)
选项。我很高兴在支持它的语言中使用
if (~value)
或if (not value)
,但是!
也太容易合并 waaaaay与变量名称或左大括号或 |或||运营商......至少在我看来。另外,有两件事:
if (value == true)
,而且我知道我不一致。尽管在我看来一致性非常重要,但令人讨厌的!
简直更糟糕。I prefer the second option, the
if (value == false)
one.I gladly use
if (~value)
orif (not value)
in languages that support it, but that!
just merges waaaaay too easily either with the variable name or opening braces or | or || operators... at least in my opinion.Also, two things:
if (value == true)
, and I'm aware I'm inconsistent. And although consistency is very important in my opinion, that pesky!
is simply worse.我使用 if (value == false)
这 ! if (!value) 太小了,我有时会错过它。
I use if (value == false)
The ! in if (!value) is so small I sometimes miss it.
无论
if
块应评估什么条件才能执行,都必须评估为true
。因此,当
value
为false
时,if (!value)
允许执行if
块的原因是因为!
运算符本质上是将value
的false
值翻转为true
,从而使括号内的结果条件成立评估为if
块执行所需的true
值。if (value)
、if (!value)
、if (flag == value)
、if (value == true)
、if (value == false)
是有效的代码,具体取决于要实现的目标。例如,当value
是可为 null 的布尔值时,if (value == true)
非常有用,因为if (value)
会给出语法错误,如果在if
块之前没有确保value
不为 null,则if (value.Value == true)
将抛出异常被执行。Whatever condition an
if
block should evaluate in order to execute must evaluate totrue
.Hence, when
value
isfalse
, the reason whyif (!value)
allows anif
block to execute is because the!
operator essentially flips thefalse
value ofvalue
totrue
, thus making the resultant condition within the parentheses evaluate into atrue
one that anif
block needs in order to execute.if (value)
,if (!value)
,if (flag == value)
,if (value == true)
,if (value == false)
, depending on what's to be achieved, are valid code. E.g.if (value == true)
is very useful whenvalue
is a nullable boolean, becauseif (value)
will give a syntax error, andif (value.Value == true)
will throw exception if you didn't ensure thatvalue
is not null before theif
block is executed.我还认为,在
if
中使用==
是多余的,我还有另一个建议,至少在视觉上,通过引入空格:即使使用 OpenDyslexic 作为字体,左括号
(
旁边的 not 符号!
可以是太近了,一眼就无法区分if(!created)
。I am also of the opinion that using
==
inside anif
is redundant and I have another suggestion, at least visually, by introducing spaces:Even using OpenDyslexic as font, the not sign
!
next to the opening bracket(
can be too close to distinguish it at a glanceif(!created)
.