如何处理运行时代码契约违规
上周我访问了荷兰的 devday11,了解了 Code Contract。我正在考虑实施代码契约,但我仍然不清楚以下内容。我应该如何处理应用程序中的运行时代码契约违规?
例如,我的应用程序中有一个层使用空值调用另一个层。调用的函数有一个必需的联系人,因此它会抛出合同验证错误。这应该如何处理?那么像这样的事情
public string GetOrderSomething(OrderModel order)
{
Contract.Requires(order != null);
// jibidi jibeda do something
}
//other application layer
private void something()
{
Class.GetOrderSomething(null);
}
应该做什么呢?我应该用正常的 try catch 来处理它,还是根本不应该处理它?我应该做一些“特别”的事情吗?
I visited devday11 in the Netherlands last week and learned about Code Contract. I am thinking about implementing Code Contract, but the following is still unclear to me. How should I handle runtime code contract violations in my application?
For example I have a layer in my application that calls another layer with a null value. The function called had a Required Contact, so it throws a contract validation error. How should this be handled? So something like this
public string GetOrderSomething(OrderModel order)
{
Contract.Requires(order != null);
// jibidi jibeda do something
}
//other application layer
private void something()
{
Class.GetOrderSomething(null);
}
What should be done? Should I handle it with a normal try catch, should I not handle it at all? Is there something "special" I should do?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
对于这种情况,如果存在
if (order == null) { , 您应该执行通常会执行的操作
抛出新的 ArgumentNullException();
但是,
这个 CodeContract 并不意味着该类已经不稳定,只是因为您向该方法传递了错误的参数...
如果这将是某个内部成员的 Requires 并且您知道它永远不应该为 null,那么那就是另一个故事了。您将有一个永久无法工作的类,如果您无法通过捕获来“修复它”,那么可能应该引发一些致命异常并发出警报。
For this case you should do what you normally would do if there was
if (order == null) {
throw new ArgumentNullException();
}
This CodeContract does not mean the class has been destabilized just that you passed a wrong parameter to the method...
However if this would be a Requires for some internal member and you know it should never be null, well that is another story. You would have a permanently unworkable class, and if you are unable to 'fix it' through catching, then probably some fatal exception should be raise and alerted.
假设您已经制定了“异常处理”政策,那么您不必执行任何特殊操作。
如果建议选择一个特定的异常:
现在您可以以与不使用合约(之前)相同的方式和位置处理 ArgumentNullException。
PS:希望你喜欢这次演讲。
Assuming you already have an 'exception handling' policy in place, you should not have to do anything special.
If would be advisable to pick a specific exception:
Now you can handle the ArgumentNullException in the same manner and place(s) as you would without (before) using contracts.
PS: Hope you liked the talk.
在我看来,Codecontracts 应该用于在运行时查找编程错误。
因此,代码契约违规执行应该像其他编程错误异常(即 IndexOutOfBoundException)一样处理
In my opinion Codecontracts should be used to find programming errors at runtime.
Therefore codecontract-violation-execptions should be handled like avery other programming-error-exception (i.e. IndexOutOfBoundException)