Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best practice in case one argument is null?

when validating methods' input, I used to check if the argument is null, and if so I throw an ArgumentNullException. I do this for each and every argument in the list so I end up with code like this:

 public User CreateUser(string userName, string password, 
                            string Email, string emailAlerts, 
                            string channelDescription)
    {

        if (string.IsNullOrEmpty(userName))
            throw new ArgumentNullException("Username can't be null");

        if (string.IsNullOrEmpty(Email))
            throw new ArgumentNullException("Email can't be null");
       //etc, etc, etc
    }

Is this OK? Why should I do this? Would it be ok if I simply group all the checks and return a null value instead of throwing the exception? What is the best practice to address this situation?

PS: I want to change this, because with long methods, it gets very tedious to do so.
Ideas?

like image 732
Galilyou Avatar asked Jul 21 '09 11:07

Galilyou


People also ask

How do you pass null as an argument?

You can pass NULL as a function parameter only if the specific parameter is a pointer. The only practical way is with a pointer for a parameter. However, you can also use a void type for parameters, and then check for null, if not check and cast into ordinary or required type.

Why is checking for null a good practice?

It is a good idea to check for null explicitly because: You can catch the error earlier. You can provide a more descriptive error message.

What is null argument?

The terms 'null argument', 'missing argument', and 'argument ellipsis' refer to the omission from a clause of one or more of three types of nominals required by the main verb: the surface Subject, the Direct Object, and/or the Indirect Object.

Is it good to pass null?

As with most method calls, it's good practice to avoid passing a null reference, which will likely result in a NullPointerException at runtime.


1 Answers

Make an ArgChecker class with something like this

  ArgChecker.ThrowOnStringNullOrEmpty(userName, "Username");

where ThrowOnStringNullOrEmpty is

  public static void ThrowOnStringNullOrEmpty(string arg, string name)
  {
      if (string.IsNullOrEmpty(arg))
        throw new ArgumentNullException(name + " can't be null");
  }

You could also try to process a list of arguments using a params arg, like:

  public static void ThrowOnAnyStringNullOrEmpty(params string[] argAndNames)
  {
       for (int i = 0; i < argAndName.Length; i+=2) {
          ThrowOnStringNullOrEmpty(argAndNames[i], argAndNames[i+1]);
       }
  }

and call like this

  ArgChecker.ThrowOnAnyStringNullOrEmpty(userName, "Username", Email, "email");
like image 165
Lou Franco Avatar answered Oct 20 '22 02:10

Lou Franco