is this overkill for assessing Main(string[] args)

后端 未结 5 1884
無奈伤痛
無奈伤痛 2021-01-12 06:44

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) {              


        
5条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-01-12 06:47

    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.

    However, in situations where such a null check does make sense, it must be the leftmost condition.

    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

提交回复
热议问题