代码合同和异常抛出的区别
我想了解代码契约的优势。我编写了以下代码(来自 PEX + 代码合约介绍)来挖掘它。
public static string TrimAfter(string value, string suffix)
{
// <pex>
Contract.Requires(suffix != (string)null);
Contract.Requires
(value.IndexOf(suffix) >= 0 && value.Length >= value.IndexOf(suffix));
Contract.Requires(value != (string)null);
// </pex>
int index = value.IndexOf(suffix);
if (index < 0)
return value;
return value.Substring(0, index);
}
我用 null 参数调用了这个方法,并且它被编译了。 所以我不清楚为什么它比抛出异常更好。 你们能解释一下代码合约是否真的有任何附加功能吗? :) 提前致谢。
I'm tying to understand Code Contracts advantages. I've wrote following code (from PEX + Code Contract introduction) to dig it.
public static string TrimAfter(string value, string suffix)
{
// <pex>
Contract.Requires(suffix != (string)null);
Contract.Requires
(value.IndexOf(suffix) >= 0 && value.Length >= value.IndexOf(suffix));
Contract.Requires(value != (string)null);
// </pex>
int index = value.IndexOf(suffix);
if (index < 0)
return value;
return value.Substring(0, index);
}
I called this method with nulls arguments and it was compiled.
So it is not clear for me why it is better then throwing Exceptions.
Could you guys explain me if Code Contracts really has any additional features? :)
Thanks in advance.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
除了提出的其他观点之外,契约还可以应用于接口(对于常规异常,您无法做到这一点),并通过继承强制执行(对于常规异常,您将很难做到这一点)。
In addition to other points made, contracts can be applied to interfaces (you couldn't do that with regular exceptions) and are enforced through inheritance (something else you'd be very hard pressed to do with regular exceptions).
问题是要让静态检查器满意需要做很多工作。我不确定对于大多数程序来说这是否值得付出努力。但也许诸如空检查之类的受限子集可以很好地发挥作用。
对我来说重点是。我很懒,如果写支票变得更容易,我更有可能添加额外的支票。特别是,我发现旧式参数 null 检查有点冗长。
另一方面,解析 IL 并识别旧标准模式进行前置条件检查并使用它生成文档应该不难。
The problem with this it is quite a bit of work to make the static checker happy. And I'm not sure if it's worth the effort for most programs. But perhaps a restricted subset such as null-checks could work well.
The main point for me. I'm lazy and if writing checks gets easier I'm more likely to add additional checks. In particual I found the old style argument null checks a bit verbose.
On the other hand it shouldn't be hard to parse the IL recognizing the old standard pattern for pre-condition checks and use that generate documentation.
为了不让它编译,您需要带有静态检查器的高级版代码合约: http ://msdn.microsoft.com/en-us/devlabs/dd491992.aspx
To not let it compile, you need the premium edition of code contracts with static checker: http://msdn.microsoft.com/en-us/devlabs/dd491992.aspx
我会猜测,但是,从文档中:
此处提供了工具。
I'm going to guess but, from the docs:
Tools are available here.