我们正在构建业务应用程序而不是其他人使用的API,在这种情况下,我更喜欢在if/then/throw模型中使用我们的验证逻辑.有人告诉我,最好使用代码合同.我没有看到任何好处,有没有明显的好处,我没有看到?我看到使用代码契约的问题,因为它是静态方法调用,并且在编译阶段之后还会发生一些代码注入.谢谢
有两个明显的好处:
(1)代码更容易阅读.
Contract.Requires(someParam != null && someParam.SomeValue != 0);
Run Code Online (Sandbox Code Playgroud)
与
if (someParam != null && someParam.SomeValue != 0)
throw new ArgumentNullException("someParam", someParam, "someParam can't be null and someParam.SomeValue can't be zero.");
Run Code Online (Sandbox Code Playgroud)
此外,使用代码约定,谓词代码会自动放入失败消息中,因此您不需要像使用普通异常一样编写显式消息.
(2)您可以对代码运行Code Contracts静态分析,它可以为您找到错误.
有一些不太明显的好处:
(3)您可以在XML doc文件中生成代码契约的文档.
(4)您可以Contract.Ensures()用来表达后条件约束.这允许你避免很多代码,if (item.Property1 != null && item.Property1.Property2 != null) ...因为你会知道它们都不是Property或者Property2可以为null.
(5)代码契约形成一个明显与代码其余部分分开的块.