抛出异常 vs Contract.Requires<T>? [英] Throwing an exception vs Contract.Requires&lt;T&gt;?

查看:18
本文介绍了抛出异常 vs Contract.Requires<T>?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是应该抛出异常还是调用合同.需要

I'm wondering whether should I throw exceptions or call Contract.Requires<TException>

例如:

public static void Function(String str)
{
    if (str == null) throw new ArgumentNullException("str", "Input string cannot be null.");

    // ...
}

对比

public static void Function(String str)
{
    Contract.Requires<ArgumentNullException>(str != null, "Input string cannot be null.");

    // ...
}

由于 Contract.Requires 不需要 CONTACTS_FULL 符号,我也可以将它保留在我的发布版本中.

Since Contract.Requires<TException> doesn't require the CONTRACTS_FULL symbol I can keep it in my release builds as well.

这是我的考虑:

缺点:您不能调用自定义异常类型构造函数的重载版本.根本没有办法向构造函数传递额外的参数.

Con: You can't call an overloaded version of the custom exception type constructor. There is simply no way to pass additional parameters to the constructor.

优点:支持静态工具(例如,通知调用方违反合同).

Pro: Static tools support (e.g. inform the caller of contract violation).

我应该使用哪一种,在什么样的情况下使用?

Which one should I use, and for what kind of situation?

推荐答案

if-then-throwRequires 之间的基本权衡,如中所述CodeContract 用户指南介绍了如何使用发布位进行构建.

The basic trade-off between if-then-throw and Requires<TException> as documented in the CodeContract user guide is how you build with your release bits.

案例 1:您只使用 if-then-throw,没有 Requires.在这种情况下,您无需在 dll/exe 上运行合同工具即可构建发布位.优点是您可以更快地构建并且没有工具引入错误的风险.第二个优势是团队成员可以选择不使用 CodeContract 工具.缺点是你没有得到requires的契约继承,你的契约不一定对工具可见(除非你使用EndContract).您可以使用汇编模式指定这种情况:自定义参数验证

Case 1: You only use if-then-throw, no Requires<TException>. In this case you can build your release bits without running the contract tools on your dll/exe. The advantage is that you have faster builds and no risk that the tool introduces bugs. A second advantage is that team members can opt out of using the CodeContract tools. Disadvantages are that you get no contract inheritance of requires, and your contracts are not necessarily visible to the tools (unless you use EndContract). You specify this case by using assembly mode: Custom Parameter Validation

Case2:您决定始终在您的发布位上运行 CodeContract 工具.这让您可以使用 Requires<TException> 并获得契约的继承,包括接口的检测等.您的契约干净且工具可识别.缺点是每个构建代码的人都必须安装 CodeContracts 工具.您可以使用装配模式指定这种情况:合同属性窗格中的标准.

Case2: You decide to run the CodeContract tools on your release bits always. This lets you use Requires<TException> and you get inheritance of contracts, including instrumentation of interfaces etc. Your contracts are clean and tool recognizable. The disadvantage is that everyone building your code must have the CodeContracts tools installed. You specify this case by using assembly mode: Standard in the Contract property pane.

希望这能解决问题.

这篇关于抛出异常 vs Contract.Requires<T>?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆