Liskov signature principle, background and abstract methods

The Liskov Signature Principle (LSP) says:

Preconditions cannot be strengthened in a subtype.

In C #, I could break the whole principle as follows:

public class A 
{
      public virtual void DoStuff(string text)
      {
            Contract.Requires(!string.IsNullOrEmpty(text));
      }
}

public class B : A
{
      public override void DoStuff(string text)
      {
            Contract.Requires(!string.IsNullOrEmpty(text) && text.Length > 10);
      }
}

But what happens if there A.DoStuffis abstract:

public class A 
{
      public abstract void DoStuff(string text);
}

public class B : A
{
      public override void DoStuff(string text)
      {
            Contract.Requires(!string.IsNullOrEmpty(text));
      }
}

Now A.DoStuffis limitless. Or his contract is all that is allowed.

So, B.DoStuffdoes the premise violate the Liskov substitution principle?

+4
source share
3 answers

It depends on what the contract defines .

LSP - , , , # " ".

:

  • "" , Contract.Requires

. , ! :

public interface StuffContainer
{
    void Add(string text);

    // Removes a string that has previously been added.
    void Remove(string text);
}

Remove . , , , LSP. , 5 , LSP.

+2

, , #.

:

: phi (x) - , x T. phi (y) y S, S - T.

B DoStuff, , , A . , .

, . " ", , .

+1

, . , . , , LSP.

Saying A.DoSomething()is irresistible, is a false premise. A.DoSomehing()undefined, so he cannot have a contract beyond his signature.

0
source

Source: https://habr.com/ru/post/1662783/


All Articles