非空接口代码契约实现 - 默认(T)VS抛NotImplementedException [英] Implementation of non-void interface Code Contracts - default(T) vs throw NotImplementedException

查看:205
本文介绍了非空接口代码契约实现 - 默认(T)VS抛NotImplementedException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这可能是风格大多是问题,但定义非void接口成员,代码合同时,哪种方法是最好的:

This may be mostly a question of style but when defining code contracts for non-void interface members, which approach is best:

接口:

[ContractClass(typeof(IFooContract))]
public interface IFoo
{
    object Bar();
}



合同选项1:

Contract option 1:

[ContractClassFor(typeof(IFoo))]
public abstract class IFooContract : IFoo
{
    object IFoo.Bar()
    {
        Contract.Ensures(Contract.Result<object>() != null);
        throw new NotImplementedException();
    }
}



合同选项2:

Contract option 2:

[ContractClassFor(typeof(IFoo))]
public abstract class IFooContract : IFoo
{
    object IFoo.Bar()
    {
        Contract.Ensures(Contract.Result<object>() != null);
        return default(T);
    }
}



大多数我见过的文献倾向于选择2,但我觉得选择1比较好,因为它是清晰的,这纯粹是关于合同(和选项2,技术上打破它刚刚定义的合同)。

Most of the literature I've seen tend towards option 2 but I feel that option 1 is better as it is clearer that this is purely about the contract (and option 2 is technically breaking the contract it just defined).

是那里有选项2优于选项1的任何方案?

Are there any scenarios where option 2 is preferred over option 1?

推荐答案

抛出异常在语义上更正确的,因为合同类可不再被调用,并在一个看似合理的方式使用;来电者将被停止,并告诉他们的错误。

Throwing an exception is semantically more correct, because the contract class can no longer be invoked and used in a seemingly reasonable way; callers will be stopped and told about their error.

然而, NotImplementedException 似乎并没有被正确的例外抛出:那异常通常标志着一个尚未实现的代码(如方法体)的部分。但非 - 无效合同法的的实施;它只是不意味着被调用。因此,我宁愿一个出现InvalidOperationException 引发NotSupportedException

However, NotImplementedException does not seem to be the proper exception to throw: That exception usually marks a section of code (such as a method body) that has yet to be implemented. But a non-void contract method has been implemented; it just isn't meant to be called. Thus I would prefer an InvalidOperationException or a NotSupportedException.

(你甚至可以引发自定义异常类型,例如一个 NotMeantToBeCalledException

(You could even throw a custom exception type, e.g. a NotMeantToBeCalledException.)

这篇关于非空接口代码契约实现 - 默认(T)VS抛NotImplementedException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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