I've just installed Microsoft Code Contracts. It's a part of .NET Framework and Visual Studio add-on. It provides runtime checking and static checking of defined contracts.
The tool has four warning levels so I set up the highest.
I've declared classes designed to violate Liskov Substitution Principle.
public class Person
{
protected int Age { get; set; }
public Person(int age)
{
Contract.Requires(age > 0);
Contract.Requires(age < 130);
this.Age = age;
}
}
public class Child : Person
{
public Child(int age) : base(age)
{
Contract.Requires(age > 0);
Contract.Requires(age < Consts.AgeOfMajority);
Contract.Requires(age < 130);
this.Age = age;
}
}
public static class Consts
{
public readonly static int AgeOfMajority = 18;
}
LSP states:
if S is a subtype of T, then objects of type T may be replaced with objects of type S without altering any of the desirable properties of that program
In my example the violation would be this asignment: Person person = new Child(23);
. We should be able to do this, but we can't because children can't be older than some age smaller than required by person class.
The result of analysis however is surprising CodeContracts: Checked 11 assertions: 11 correct
. Is my example wrong or Code Contracts don't detect such things?