代码契约和表单控件
我正在尝试掌握代码契约,因为我认为这个概念在生成更健壮的代码方面前景广阔,但到目前为止,有很多事情对我来说仍然不清楚或看起来很麻烦。
我目前遇到的最大问题之一是如何正确处理表单控件。在静态检查选项中选择“隐式非空义务”后,我收到一条消息,建议为当前表单中的每个控件推荐一个 Contract.Requires([control] != null)
规则,该规则我访问;这有点毫无意义,因为我知道控件将始终存在,因为它们是在表单的 InitializeComponent()
方法中创建的。
我知道静态检查器无法知道这一点,但必须有一种方法来消除这些消息(如果只是因为它们使列表变得混乱) - 至少我希望如此 - 除了明显添加所有建议的检查(或者也许是 Contract.Assume()
调用),这会使我的代码变得混乱,同时实际上(逻辑上)是冗余的。
处理这个问题的正确方法是什么?为所有控件添加不变规则,要求它们始终为非空?那我知道永远存在的对象成员呢,比如 ComboBox.Items ?
感谢您分享对此的任何见解。
I'm trying to get a grip on Code Contracts as I think the concept holds great promise in regards to producing more robust code, but so far quite a few things are still unclear to me or seem cumbersome.
One of the biggest questions I currently have is how to correctly handle form controls. With "Implicit Non-Null Obligations" selected in the static checking options, I get a message recommending a Contract.Requires([control] != null)
rule for each and every control within the current form which I access; this is a little pointless because I know the controls will always be there as they are created in the form's InitializeComponent()
method.
I know the static checker cannot know about that, but there has to be a way of getting rid of those messages (if only because they clutter up the list) - at least I hope so - other than the obvious adding all those recommended checks (or maybe rather Contract.Assume()
calls), which would then clutter up my code while being effectively (logically) redundant.
What is the correct way to deal with this ? Adding invariant rules for all the controls requiring them to always be non-null ? And what about the object members that I know will always be there, like ComboBox.Items
?
Thanks for sharing any insights on this.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
处理它的最简单方法是添加这样的对象不变量:
我认为您还需要
假设
在InitializeComponent
调用之后这些不为空,因为代码契约不知道其中发生了什么(代码契约需要这样做来证明构造函数末尾的不变量成立)。完成此操作后,静态检查器将知道这些不变量在构造函数的末尾保持不变(即控件不为空),并且它们在任何其他方法中始终不为空。
对于诸如
ComboBox.Items
之类的其他内容,您现在必须Assume
,因为它们在 BCL 中没有合约。您可以请求在The simplest way to deal with it is to add object invariants like this:
I think you'll also need to
Assume
that these are not-null after theInitializeComponent
call, since Code Contracts doesn't know what happens inside that (this is needed for Code Contracts to prove that the Invariants hold by the end of the constructor).Once you've done that, the static checker will know that these invariants hold (i.e. the controls are not-null) at the end of the constructor, and that they will always be not-null in any other methods.
For other things like
ComboBox.Items
, you'll have toAssume
for now, since they don't have contracts in the BCL. You can request for contracts to be added in this thread on the Code Contracts forum.