Liskov 替换原理、前提条件和抽象方法 [英] Liskov substitution principle, preconditions and abstract methods

查看:36
本文介绍了Liskov 替换原理、前提条件和抽象方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Liskov 替换原则 (LSP) 说:

Liskov substitution principle (LSP) says:

不能在子类型中加强先决条件.

Preconditions cannot be strengthened in a subtype.

在 C# 中,我可能会违反整个原则,如下所示:

In C#, I could violate 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);
      }
}

但是,如果 A.DoStuff 是一个 abstract 方法会发生什么:

But, what would happen if A.DoStuff would be an abstract method:

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

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

现在 A.DoStuff无合约.或者它的合同只是允许的一切.

Now A.DoStuff is contractless. Or its contract is just everything allowed.

那么,B.DoStuff 前提条件是否违反了Liskov 替换原则?

So, is B.DoStuff precondition violating Liskov substitution principle?

推荐答案

这取决于契约的定义.

LSP 是一种理论结构,它不依赖于特定的语言或实现,例如 C# 的代码契约"功能.

The LSP is a theoretical construct, it does not depend on a specific language or implementation, such as C#'s "Code Contracts" feature.

合约可以通过以下方式定义:

The contract can be defined by:

  • 方法名
  • 方法参数名称
  • 方法注释
  • 返回类型和方法参数类型
  • 显式"合约,例如 Contract.Requires

最后两个会被编译器验证.但是,前三个也可以成为合同的一部分!考虑以下示例:

On the last two will be verified by the compiler. However, the first three can be part of the contract as well! Consider the following example:

public interface StuffContainer
{
    void Add(string text);

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

Remove 方法的名称和文档定义了一个明确的前提条件.在实现中验证要删除的字符串先前已添加不会违反 LSP.验证字符串至少有 5 个字符会违反 LSP.

The name and the documentation of the Remove method define a clear precondition. Verifying in an implementation that the string to be removed has previously been added does not violate the LSP. Verifying that the string has at least 5 characters would violate the LSP.

这篇关于Liskov 替换原理、前提条件和抽象方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆