Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the correct way to validate the arguments of a constructor

So I have a class with a single string parameter in its constructor:

public MyClass(string name)
{
    this.Name = name;
}

but I never want to worry about some one initializing an instance of MyClass with name that is NULL or a zero length string. What is the best was to validate the parameter? With a property or method you can always just do nothing, return null, or not set anything if an invalid argument is provided. But once a constructor is called the instance of the object is already created regardless of whether it was passed valid arguments.

Is throwing an exception as shown below the best way? Or is there some other method that's more preferred?

public MyClass(string name)
{
    if (name == null | name == "") throw new ArgumentException("Name can not be null or blank", "name");

    this.Name = name;
}

Of course I could always set the name to some default like "Unnamed MyClass" if the argument is invalid, but in this case I'd rather just prevent an invalid name then trying to assume some alternate behavior.

like image 987
Eric Anastas Avatar asked Jul 21 '09 03:07

Eric Anastas


1 Answers

  1. Throw an ArgumentNullException
  2. Document that the ctor throws ArgumentNullException if name is null
  3. If you are using Code Contracts, add a Contract.EndContractBlock() line after your parameter validation.

Edit: Instead of this:

if (name == null || name == "")

Use this:

if (string.IsNullOrEmpty(name))
like image 134
Sam Harwell Avatar answered Oct 08 '22 01:10

Sam Harwell