按契约和类不变式设计

发布于 2024-08-14 17:23:05 字数 190 浏览 5 评论 0原文

我正在阅读有关 dbc 的内容 (http://en.wikipedia.org/wiki/Design_by_contract ) 有人可以给我一个使用与继承相关的类不变量的简单例子吗?

I'm reading about dbc (http://en.wikipedia.org/wiki/Design_by_contract)
Can someone please give me a simple example of using class invariants in relation to inheritance?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

彩扇题诗 2024-08-21 17:23:05

当契约概念适用于面向对象语言时,设计会变得稍微复杂一些。

类不变量是一个属性,在调用方法时保证类的每个实例都具有该属性(就像所有方法的公共前提条件),并且作为回报,每个方法和构造函数必须确保在终止时保持 true(例如常见的后置条件)。

它们适合表达一致性条件。对实际钱包进行建模的 Wallet 类可能具有类不变量,即所包含的金额始终为正数。

类不变量与契约的其余部分一样,是继承的。方法的新实现必须提供与其替换的方法相同的保证。

Design by contract concepts get slightly complicated when they are adapted to object-oriented languages.

A class invariant is a property that each instance of the class is guaranteed to have when a method is called (like a common pre-condition for all methods), and that in return each method and constructor must ensure remains true when they terminate (like a common post-condition).

They are good for expressing consistency conditions. A Wallet class that modelizes an actual wallet might have the class invariant that the amount contained is always positive.

Class invariants, like the rest of the contract, are inherited. New implementations of methods must provide the same guarantees as the methods they replace.

月野兔 2024-08-21 17:23:05

在继承的类中,不变量应该至少同样严格,但它们可以更严格。如果派生类中省略了不变量,则基类的不变量当然适用。

例如:

// Class invariant : sum should be > -1000
Account { public int sum; }

// Class invariant : sum should be >= 0
AccountForKids : inheritsFrom Account { public int sum; }

儿童帐户不应低于零,但当然大于-1000。

一般来说:当类不变量变得更严格时,派生类的契约总是受到尊重。

In the inherited class, the invariants should be at least equally strict, but they can be stricter. If an invariant is omitted in a derived class, the invariants of the base class apply of course.

eg :

// Class invariant : sum should be > -1000
Account { public int sum; }

// Class invariant : sum should be >= 0
AccountForKids : inheritsFrom Account { public int sum; }

The account for kids shouldn't go beneath zero, but that of course is bigger than -1000.

In General : The contract of a derived class is always hounoured when the class invariants become stricter.

回梦 2024-08-21 17:23:05

派生类不变量应该:

  • 检查派生类中引入的任何成员变量的不变量
  • 检查基类的不变量

A derived class invariant should:

  • Check the invariants of any member variables introduced in the dervied class
  • Check the invariant of the base class
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文