Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

main

c#

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 
    }
}

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?

like image 240
whytheq Avatar asked Mar 19 '12 08:03

whytheq


2 Answers

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

like image 189
jalf Avatar answered Oct 03 '22 00:10

jalf


According to this, you only need to check :

if (args.Length == 0)
{
    // Do X
}

Though checking for null doesn't do any harm, there is no real need.

like image 31
ApprenticeHacker Avatar answered Oct 02 '22 22:10

ApprenticeHacker