I found this statement is some old code and it took me a second to figure out...
我发现这个陈述是一些旧代码,我花了一秒钟才弄明白......
IsTestActive = (TestStateID == 1 ? true : false);
Please correct me if I'm wrong but isn't this the same as this one?:
如果我错了请纠正我,但这不是这个吗?:
IsTestActive = (TestStateID == 1);
If it is, why would you ever want to use the first? Which one is more readable? (I think the latter, but I'd like to see what others think.)
如果是的话,你为什么要用第一个呢?哪一个更具可读性? (我认为后者,但我想看看其他人的想法。)
5 个解决方案
#1
Yes, it is exactly the same.
是的,它完全一样。
Yes, the latter is more readable.
是的,后者更具可读性。
#2
IsTestActive = (TestStateID == 1);
is definitely more readable.
绝对更具可读性。
You could make a case for defining a constant
您可以为定义常量做一个案例
ACTIVE = 1
then replacing the boolean variable IsTestActive
with
然后用。替换布尔变量IsTestActive
(TestStateID == ACTIVE)
The way the code is now, the state of the boolean IsTestActive
will be erroneous if the state of TestStateID
changes without updating the boolean. Bypassing the boolean and testing the real source of the information you're after will remove the possibility of this error.
现在代码的方式,如果TestStateID的状态发生更改而不更新布尔值,则布尔IsTestActive的状态将是错误的。绕过布尔值并测试您所追踪的信息的真实来源将消除此错误的可能性。
#3
No, there's no practical reason for using the first version, world isn't perfect, and neither are programmers.
不,使用第一个版本没有实际的理由,世界并不完美,也不是程序员。
#4
Readability depends on where you use this construct. I often find something like
可读性取决于您使用此构造的位置。我经常发现类似的东西
(TestStateID == 1 ? true : false)
more readable.
#5
Well, I don't know about other languages, but in PHP it's even more easy, using type-casting:
好吧,我不知道其他语言,但在PHP中,使用类型转换更容易:
$IsTestActive = (boolean)$TestStateId;
#1
Yes, it is exactly the same.
是的,它完全一样。
Yes, the latter is more readable.
是的,后者更具可读性。
#2
IsTestActive = (TestStateID == 1);
is definitely more readable.
绝对更具可读性。
You could make a case for defining a constant
您可以为定义常量做一个案例
ACTIVE = 1
then replacing the boolean variable IsTestActive
with
然后用。替换布尔变量IsTestActive
(TestStateID == ACTIVE)
The way the code is now, the state of the boolean IsTestActive
will be erroneous if the state of TestStateID
changes without updating the boolean. Bypassing the boolean and testing the real source of the information you're after will remove the possibility of this error.
现在代码的方式,如果TestStateID的状态发生更改而不更新布尔值,则布尔IsTestActive的状态将是错误的。绕过布尔值并测试您所追踪的信息的真实来源将消除此错误的可能性。
#3
No, there's no practical reason for using the first version, world isn't perfect, and neither are programmers.
不,使用第一个版本没有实际的理由,世界并不完美,也不是程序员。
#4
Readability depends on where you use this construct. I often find something like
可读性取决于您使用此构造的位置。我经常发现类似的东西
(TestStateID == 1 ? true : false)
more readable.
#5
Well, I don't know about other languages, but in PHP it's even more easy, using type-casting:
好吧,我不知道其他语言,但在PHP中,使用类型转换更容易:
$IsTestActive = (boolean)$TestStateId;