Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to violate Liskov Substitution Principle in a constructor?

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?

like image 619
Arkadiusz Kałkus Avatar asked Mar 05 '16 15:03

Arkadiusz Kałkus


1 Answers

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.

like image 190
weston Avatar answered Sep 20 '22 09:09

weston