.net - 引用另一个约定方法时是否应该重复条件?

标签 .net c#-4.0 code-contracts

以下是接口(interface)合约的摘录。

我的问题是:前一种方法是否应该重复后一种方法的前提条件?由于契约(Contract)是公开的,是否可以省略重复?在本例中,它只是一个非空检查,但我可以想象这样的情况:重复大量代码,并且由于在运行时重复相同的检查而导致性能受到影响。

public int CommandConsumerCount(IWriteCommand writeCommand)
{
    Contract.Requires(writeCommand != null); // redundant?
    Contract.Requires(this.IsOwnerOf(writeCommand));

    Contract.Ensures(Contract.Result<int>() >= 0);

    return default(int);
}

public bool IsOwnerOf(IWriteCommand writeCommand)
{
    Contract.Requires(writeCommand != null);

    return default(bool);
}

最佳答案

这在某种程度上取决于该条件(在本例中为 writeCommand != null)是否是 CommandConsumerCount 方法和 IsOwnerOf 方法的要求,或者是否仅是 IsOwnerOf 方法的要求。

如果该条件仅是 IsOwnerOf 方法真正需要的,那么可以从 CommandConsumerCount 方法中省略它。

但是,如果这两种方法都需要该条件,那么我坚持下面的原始答案:

我认为,由于您的两种方法都是公开的,因此应该重复契约(Contract)要求。如果您有一个执行实际工作的私有(private)方法,IsOwnerOf 方法和 CommandConsumerCount 方法都调用该方法(而不是调用 IsOwnerOf 方法的 CommandConsumerCount 方法),那么在该方法中省略对 Contract.Requires 的调用就可以了。私有(private)方法。

就性能而言...我不会担心这些检查对性能的影响,除非检查本身的逻辑非常复杂。您可以设置编译器以从项目属性的“代码契约(Contract)”部分的编译输出中排除对 Contract.Requires 的调用(假设您安装了必要的插件)。

不过,也许我没有捕获你问题的要点。您是否询问是否可以完全省略 CommandConsumerCount 方法内部对 IsOwnerOf 的调用?在这种情况下,我会将调用保留在适当的位置,但如果这是一个性能问题,那么我将配置项目以排除对发布版本的调用,假设我已经使用调试版本进行了足够的测试以确保此条件满足满意。

编辑:重新阅读问题后,很明显您正在询问 writeCommand != null检查一下,所以我删除了上面的段落。

下面的代码示例添加了执行 IsOwnerOf 方法实际工作的私有(private)方法。

    // you may want to choose a different name for this method
    private bool _IsOwnerOf(IWriteCommand)
    {
        // actual work is done here in this private method
        return default(bool);
    }

    public bool IsOwnerOf(IWriteCommand writeCommand)
    {
        Contract.Requires(writeCommand != null);

        // call the private method to perform the actual work
        return _IsOwnerOf(writeCommand);
    }

    public int CommandConsumerCount(IWriteCommand writeCommand)
    {
        Contract.Requires(writeCommand != null);
        Contract.Requires(_IsOwnerOf(writeCommand)); // call the private _IsOwnerOf method instead of the public method

        Contract.Ensures(Contract.Result<int>() >= 0);

        return default(int);
    }

关于.net - 引用另一个约定方法时是否应该重复条件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9262592/

相关文章:

.net - Visual Studio 属性面板

c# - 如何将 A<T> 类型的泛型对象转换为 A<T'>?

c#-4.0 - MEF 和工厂模式

c# - 代码契约、继承和里氏原理

c# - 为什么我通过 C# 代码得到格式错误的契约(Contract)?

具有生成器模式的 C# 代码契约(Contract) - "Possibly calling a method on a null reference"

c# - 如何使用 C# 在 x 轴 MSChart 中设置值

c# - 使用 .NET 中的 linq 计算 dataGridView 中列的不同值

C# - switch 语句内的 goto 挂起

c#-4.0 - 如何从 Gmail 获取电子邮件