记录接口抛出异常是一种好习惯吗?

Xiy*_*yng 10 c# interface

正如标题所说:记录抛出的接口异常是一种好习惯吗?是否存在普遍认可的最佳实践?我觉得这是一个不应该以任何方式包含在界面中的实现细节,但同时我觉得界面的用户应该拥有有价值的信息.

这样的评论是否是一个好的做法是另一个讨论的主题,所以为了限制这个问题的范围,我们假设我们已经同意用这样的评论来记录代码是一个好习惯.这里有'像这样的评论',我的意思是你可以从中产生一些东西,比如文档或元数据,而不仅仅是'正常'评论.示例包括XML文档,Javadoc和Doxygen.

现在,如果有任何最佳实践甚至可以达成一致,那么这些C#示例中的哪一个是更好的做法?

接口无异常文档:

public interface IMyInterface {
    /// <summary>
    /// Does something.
    /// </summary>
    void DoSomething();
}
Run Code Online (Sandbox Code Playgroud)

与异常文档的接口:

public interface IMyInterface {
    /// <summary>
    /// Does something.
    /// </summary>
    /// <exception cref="System.Exception">Something went wrong.</exception>
    void DoSomething();
}
Run Code Online (Sandbox Code Playgroud)

Sco*_*ain 10

接口是契约,如果该合同的一部分包含抛出异常的情况,则应将其明确地包含在文档中.您可以看到整个.NET框架中的接口中记录的异常示例,例如,IEnumerator有很多例外.(通过右键单击声明IEnumerator并导航到"元数据视图"来检索文本)

  public interface IEnumerator
  {
    /// <summary>
    /// Advances the enumerator to the next element of the collection.
    /// </summary>
    /// 
    /// <returns>
    /// true if the enumerator was successfully advanced to the next element; false if the enumerator has passed the end of the collection.
    /// </returns>
    /// <exception cref="T:System.InvalidOperationException">The collection was modified after the enumerator was created. </exception><filterpriority>2</filterpriority>
    bool MoveNext();
    /// <summary>
    /// Sets the enumerator to its initial position, which is before the first element in the collection.
    /// </summary>
    /// <exception cref="T:System.InvalidOperationException">The collection was modified after the enumerator was created. </exception><filterpriority>2</filterpriority>
    void Reset();
    /// <summary>
    /// Gets the current element in the collection.
    /// </summary>
    /// 
    /// <returns>
    /// The current element in the collection.
    /// </returns>
    /// <filterpriority>2</filterpriority>
    object Current { get; }
  }
Run Code Online (Sandbox Code Playgroud)

  • @DavidArno:为什么在intellisense中看到`Current`返回"集合中的当前元素"或者"MoveNext"如果"在创建枚举器后修改了集合"则抛出异常是无意义的废话使用这个属性?这是非常有价值的信息. (3认同)
  • @DavidArno嗯?你有意密集吗?*intellisense*的哪一部分你没理解?这些注释并不意味着与普通代码注释(`// ...`)类似,它们只是使intellisense能够理解并显示有关任何给定类型及其成员的有意义信息的标准方法.一点线索:`{get; 使用*intellisense*看不到``.哦,它也是如何构建MSDN文档的. (3认同)
  • @DavidArno:然后应该重写MSDN,所有类和方法应该删除已经有意义的文档. (3认同)
  • @DavidArno:您认为如果方法/属性名称有意义,最好省略文档吗? (2认同)
  • @DavidArno你是如此轻松的错误......重点是文档至少要清楚一些不太明显的信息:在这种情况下,`Current`是一个只读属性,这是一种方便当您扫描一个没用多少的课时,在智能感知中弹出的信息. (2认同)