Best way to check for null parameters (Guard Clauses)

后端 未结 10 1801
北荒
北荒 2021-01-31 16:45

For example, you usually don\'t want parameters in a constructor to be null, so it\'s very normal to see some thing like

if (someArg == null)
{
    throw new Arg         


        
10条回答
  •  盖世英雄少女心
    2021-01-31 17:29

    If you have too many parameters in your constructors, you'd better revise them, but that's another story.

    To decrease boilerplate validation code many guys write Guard utility classes like this:

    public static class Guard
    {
        public static void ThrowIfNull(object argumentValue, string argumentName)
        {
            if (argumentValue == null)
            {
                throw new ArgumentNullException(argumentName);
            }
        }
    
        // other validation methods
    }
    

    (You can add other validation methods that might be necessary to that Guard class).

    Thus it only takes one line of code to validate a parameter:

        private static void Foo(object obj)
        {
            Guard.ThrowIfNull(obj, "obj");
        }
    

提交回复
热议问题