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?
While it's true that LSP specifies a subtype can't place more restrictive preconditions on methods, this doesn't apply to constructors as you do not use constructors in a polymorphic way.
The contract violation would be new Child(23);
which occurs before assigning to a Person
.
So the example violation is wrong, it doesn't get as far as creating an instance of subtype S, let alone replacing it for T.
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