代码合约失败示例 Graph.Remove(Edge e)
这是一个简单的图形操作方法,我用代码契约来装饰它。
确保声明无法证明,但我不明白为什么!我相信它声称在调用 Remove() 后,要么该边不再在边列表中,要么结果为 false。如果结果为真,它不会声明任何有关图状态的信息。静态检查器不喜欢它,而且我还没有让 Pex 告诉我如何使用它(尽管我可能只是不知道如何使用它)。
我相信,对于这个例子来说,锁是无关紧要的,但为了以防万一,我会保留它。另外,OnRemoveEdge 的委托没有任何保证,但我现在隐式假设它不会重新进入图形代码。此外,假设是在它之后。
public bool Remove(E edge)
{
Contract.Requires(edge != null);
Contract.Ensures(!Contract.Exists(edges, e => e == edge) || !Contract.Result<bool>());
lock (sync)
{
if (!OnBeforeRemoveEdge(edge)) return false;
if (!edges.Remove(edge)) return false;
}
OnRemoveEdge(edge);
Contract.Assume(!Contract.Exists(edges, e => e == edge));
return true;
}
更新:我更改了代码以将事件处理程序 OnRemoveEdge()(但不是委托 OnBeforeRemoveEdge)移出锁定。但是,这对于合约中与线程相关的假设有什么作用呢?代码契约是否采用单线程模型?嗯。
Here's a simple graph manipulation method which I have decorated with Code Contracts.
The ensures claim won't prove but I can't see why! I believe it claims that after calling Remove(), either the edge is no longer in the edges list OR the result is false. It claims nothing about the state of the graph if the result is true. The static checker doesn't like it and I haven't gotten Pex to tell me how (though I probably just don't know how to use it).
The lock is extraneous for this example, I believe, but I'll leave it just in case. Also, the delegate for OnRemoveEdge has no guarantees, but I'll implicitly assume for now that it is not re-entrant into the Graph code. Besides, the Assumption is after it.
public bool Remove(E edge)
{
Contract.Requires(edge != null);
Contract.Ensures(!Contract.Exists(edges, e => e == edge) || !Contract.Result<bool>());
lock (sync)
{
if (!OnBeforeRemoveEdge(edge)) return false;
if (!edges.Remove(edge)) return false;
}
OnRemoveEdge(edge);
Contract.Assume(!Contract.Exists(edges, e => e == edge));
return true;
}
Update: I changed the code to move the Event handler, OnRemoveEdge(), (but not the delegate, OnBeforeRemoveEdge) out of the lock. But then, what does this do for the contract's assumption related to threads? Does Code Contracts assume a single-threaded model? Hmmm.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
来自Jack Leitch 对类似问题的回答:
真的。真的。
From Jack Leitch's answer to a similar question:
True. true.