Validating Arguments
When writing a method, arguments should be validated first before any operations are performed. For example, let's say we've got a class representing people:
public class Person
{
public readonly string Name;
public readonly int Age;
public class Person(string name, int age)
{
this.Name = name;
this.Age = age;
}
}
What's wrong with this Person class? name and age aren't validated before their values are set as fields of Person. What do I mean by "validated?" Both argument should be checked that their values are acceptable. For example, what if name's value is an empty string? Or age's value is -10?
Validating the arguments is performed by throwing ArgumentExceptions or derived exceptions when the values are unacceptable. For example:
public class Person(string name, int age)
{
if (String.IsNullOrEmpty(name))
{
throw new ArgumentNullException
("name", "Cannot be null or empty.");
}
if (age <= 0 || age > 120)
{
throw new ArgumentOutOfRangeException
("age", "Must be greater than 0 and less than 120.");
}
this.Name = name;
this.Age = age;
}
This properly validates the arguments Person's constructor receives.
Tedium ad Nauseum
Because you've been validating arguments for a long time (right?), you're probably tired of writing these if (....) throw Argument... statements in all of your methods.
You can look into Code Contracts in .NET 4.0.
You may also want to look at the FluentValidation Library on CodePlex if you don't want to wait for code contracts.
Ultimately, you still need to put the rules that govern argument values somewhere - it just a matter of deciding whether you prefer an imperative style (e.g. string.IsNullOrEmpty) or a declarative one.
Validating your inputs as is a key practice for writing solid code - but it certainly can be repetitive and verbose.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With