这是矫枉过正评估的主要(字串[] args) [英] is this overkill for assessing Main(string[] args)
问题描述
我有以下内容,想知道如果最初的测试是矫枉过正:
I've got the following and was wondering if the initial test is overkill:
static void Main(string[] args) {
if (args.Length == 0 || args == null) {
//do X
}
else {
//do Y
}
}
换句话说什么,我问的是有没有args.Length的可能性为零,或ARGS被空....还是只想其中一个条件就够了?
in other words what I'm asking is are there possibilities of args.Length being zero, or args being null....or would just one of these conditions sufficed?
推荐答案
好了,主
定义为永远永远永远永远被称为以空
参数。如果它的确实的莫名其妙收到一个空的参数,那么你的环境是如此打破了所有的赌注都关闭,不管你做什么,所以没什么好说的,以通过检查空来获得
。
Well, Main
is defined to never ever ever ever be called with a null
parameter. If it does somehow receive a null parameter, then your environment is so broken that all bets are off no matter what you do, so there's really nothing to be gained by checking for null
.
在另一方面,如果你的做的检查空,则代码的读者和维护者必须明白的为什么的。为什么放这么窝囊检查原来的程序员?他知道我们做的不是?我们不能只是将其删除,因为他可能已经发现了一些奇怪的角落情况下错误!
On the other hand, if you do check for null, then readers and maintainers of the code will have to understand why. Why did the original programmer put in such a useless check? Did he know something we don't? We can't just remove it, because he might have uncovered some weird corner case bug!
在换句话说,你增加了复杂到您的程序,并绊倒了代码的未来的读者。不要那样做。未来的用户可能的您的。让你的未来的自己开心,编写代码的有道理的
In other words, you're adding complexity to your program, and tripping up future readers of the code. Don't do that. That future user might be you. Make your future self happy, and write code that makes sense.
不过,在情况下这样的空检查的确实。EM>是有意义的,它必须是最左边的条件
However, in situations where such a null check does make sense, it must be the leftmost condition.
在这样一个测试: args.Length == 0 || ARGS == NULL
, args.Length
被评估的第一个的,如果失败, ARGS
进行比较空
。换句话说,如果 ARGS
为空,你的代码会抛出异常。它应该是 ARGS == NULL || args.Length == 0
In a test like this: args.Length == 0 || args == null
, args.Length
is evaluated first, and if that fails, args
is compared to null
. In other words, if args
is null, your code will throw an exception. It should be args == null || args.Length == 0
这篇关于这是矫枉过正评估的主要(字串[] args)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!