I just installed Microsoft Code contracts. This is part of the .NET Framework and Visual Studio add-ons. It provides performance verification and static verification of certain contracts.
The tool has four warning levels, so I set the highest.
I announced classes designed to violate the Liskov replacement 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 Status:
if S is a subtype of T, then objects of type T can be replaced by objects of type S without changing any desired properties of this program
In my example, it will be a violation of the assignment: Person person = new Child(23);. We should be able to do this, but we cannot, because children cannot be older than some age, less than what is required by a person's class.
, , CodeContracts: Checked 11 assertions: 11 correct. Code Contracts ?