Design by contract

Design by contract is a way to validate by specifying "Contracts".

The contracts should be visible to users to let them know what is expected by the method/property. This implementation do not do that yet (instead you have to describe the contracts in the documentation).

Before
void AddUser(string name, int age)
{
    if (string.IsNullOrEmpty(name))
      throw new ArgumentNullException("name");
    if (name.Length > 40)
      throw new ArgumentException("Name must be less than 40 characters.", "name");
    if (age < 0 || age > 120)
      throw new ArgumentException("Age must be between 0 and 120.", "age");

    [....]
}


After
void AddUser(string name, int age)
{
    Check.NotEmpty(name, "name");
    Check.Max(40, name, "name");
    Check.Between(0, 120, age, "age");

    [....]
}



We might create another implementation using attributes in the future:
[Max(40, true)] // true == required
public string LastName
{
   [...]
}
[Between(0, 120)]
public int Age
{
  [...]
}

Last edited Aug 25, 2008 at 4:11 PM by jgauffin, version 2

Comments

No comments yet.