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

后端 未结 5 1885
無奈伤痛
無奈伤痛 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

    0 讨论(0)
  • 2021-01-12 06:47

    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.

    0 讨论(0)
  • 2021-01-12 07:03
    if (args == null)
    {
        Console.WriteLine("args is null"); // Check for null array
    }
    else
    {
        if (args.Length == 0)
        {
            //do X
        }
        else 
        { 
            //do Y 
        }
    }
    
    0 讨论(0)
  • 2021-01-12 07:07

    If there's no input data, then args.Length is equal to 0, but not null. If there's any input data, then agrs.Length is equal to count of input arguments. In conclusion, args can't be null, but length can be zero.

    PS check for null first always

    0 讨论(0)
  • 2021-01-12 07:08

    It's never bad idea to make additional control, if this is not into the high performance, very frequent used functions. So I would say, not, it's not overkill.

    And another thing: first check for null, after for Length

    0 讨论(0)
提交回复
热议问题