Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to avoid argument validation

Validating Primitive Arguments and "Complex Data"

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.

What can we do to avoid writing String.IsNullOrEmpty a bazillion times throughout your code?

like image 872
JamesBrownIsDead Avatar asked Oct 22 '09 17:10

JamesBrownIsDead


1 Answers

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.

like image 133
LBushkin Avatar answered Oct 09 '22 01:10

LBushkin