在调用例程之后和之前在哪里评估不变量?
在契约设计中,类不变量必须在两种情况下满足:创建对象之后和调用例程之后。是否有任何示例或条件,我也必须在调用例程之前进行评估?
In the design by contracts, the class invariant must be satisfied on two occasions: after creating the object and after call a routine. Are there any examples or conditions, which I have to do the evaluation before the call to the routine too?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在功能调用之前可能会违反类不变量。情况可能有所不同,我只介绍最明显的情况:
混叠。一个对象引用类不变量中涉及的某个其他对象,并且该其他对象被第三方修改:
现在以下代码违反了类
SWITCH
的不变量:外部状态。对象与类不变量中引用的外部数据耦合,并且可能会意外更改:
现在,如果在应用程序外部修改数据库,缓存可能会变得不一致,并在以下功能调用之前触发类不变性违规:
打回来。一个对象可以以无效状态传递给另一个对象:
对
HADNLER
的回调(由STRUCTURE
类的功能iterate_over_elements
执行)会导致不变违规,因为handler
代码> 状态不佳:人们可以说所有情况都是由于软件错误和缺陷造成的,但这正是类不变量捕获包括这些情况在内的情况的目的当违规时发生在功能调用之前。
The class invariant can be violated before a feature call. The conditions may be different, I'm presenting only the most obvious ones:
Aliasing. An object references some other object that is involved in a class invariant and that other object is modified by a third party:
Now the following code violates the invariant of class
SWITCH
:External state. An object is coupled with external data that is referenced in a class invariant and may change unexpectedly:
Now if the database is modified outside the application, the cache may become inconsistent and a class invariant violation is triggered before the following feature call:
Callback. An object can be passed to the other one in an invalid state:
A callback to
HADNLER
, performed by the featureiterate_over_elements
of the classSTRUCTURE
, causes an invariant violation becausehandler
is not in a good condition:One can argue that all the cases are because of software bugs and flaws, but this is exactly the purpose of class invariants to catch those including the cases when the violation happens before feature calls.