简体   繁体   English

前后条件的强弱

[英]Strengthening and Weakening of pre and post conditions

I have been reading into the topic of Design By Contract and so far have the following notes written:我一直在阅读按合同设计的主题,到目前为止,我写了以下注释:

When strengthening a condition, it means to make it 
more restrictive and weakening a condition is the opposite. 

A subclass' pre-condition is either weaker or the same as its super class'
A subclass' post-condition is either stronger or the same as its super class'

I would like to confirm an example to clarify my understanding.我想确认一个例子来澄清我的理解。

class exampleA {
    int processInt(int exampleInt) {
        return exampleInt;
    }
}

class exampleB extends exampleA {
    int processInt(int exampleInt) {
        return exampleInt;
    }
}

Design by Contract says if the precondition for processInt in exampleA is, " exampleInt must be greater than 10," and the postcondition is, "the returned value is between 20 and 50," then the precondition of exampleB 's method exampleInt must either be the same or weaker, and the postcondition would be the same or stronger.契约式设计表示,如果exampleAprocessInt前提条件是“ exampleInt必须大于 10”,而后置条件是“返回值在 20 到 50 之间”,那么exampleB的方法exampleInt的前提条件必须是相同或更弱,后置条件将相同或更强。

This means valid preconditions for exampleB could be,这意味着exampleB的有效前提条件可能是,

  • Greater than 0大于 0
  • Greater than or equal to 0大于或等于 0
  • Greater than -100大于 -100

But invalid preconditions would be,但无效的先决条件是,

  • Greater than 20大于 20
  • In the range of 20 to 500在 20 到 500 范围内

Likewise, valid postconditions could be,同样,有效的后置条件可能是,

  • Between 25 and 45 25 至 45 岁之间
  • Between 30 and 40 30 到 40 之间

But invalid postconditions would be,但无效的后置条件是,

  • Between 20 and 90 20 到 90 之间
  • Between 0 and 50 0 到 50 之间
  • Greater than 0大于 0

Is this a correct interpretation of Design by Contract?这是对合同设计的正确解释吗? Also, I am learning this in Java, but I assume the concept applies to any language with OOP?另外,我在 Java 中学习这个,但我认为这个概念适用于 OOP 的任何语言?

Yes, your examples are correct;是的,你的例子是正确的; and yes, the same concepts apply to any language that supports polymorphism.是的,同样的概念适用于任何支持多态的语言。 Note that Design by Contract is also a part of the Liskov Substitution Principle , which prescribes even more restrictions on subtypes.请注意,按合同设计也是Liskov 替换原则的一部分,该原则对子类型规定了更多限制。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM