我一直在閱讀按合同設計的主題,到目前為止已經寫了以下筆記:
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'
我想確認一個例子來澄清我的理解。
class exampleA {
int processInt(int exampleInt) {
return exampleInt;
}
}
class exampleB extends exampleA {
int processInt(int exampleInt) {
return exampleInt;
}
}
通過契約設計說,如果先決條件為processInt在exampleA是“exampleInt必須大于10,”與后置條件是“的回傳值是20和50之間”,那么的前提exampleB的方法exampleInt必須是相同的或更弱,并且后置條件將相同或更強。
這意味著有效的先決條件exampleB可能是,
- 大于 0
- 大于或等于 0
- 大于 -100
但無效的先決條件是,
- 大于 20
- 在 20 到 500 的范圍內
同樣,有效的后置條件可以是,
- 25 到 45 之間
- 30 到 40 之間
但無效的后置條件是,
- 20 到 90 之間
- 0 到 50 之間
- 大于 0
這是對合同設計的正確解釋嗎?另外,我正在用 Java 學習這個,但我認為這個概念適用于任何帶有 OOP 的語言?
uj5u.com熱心網友回復:
是的,你的例子是正確的;是的,相同的概念適用于任何支持多型的語言。請注意,契約式設計也是Liskov 替換原則的一部分,它對子型別規定了更多限制。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/363992.html
下一篇:C 在事件偵聽器模式中包含問題
