正如标题所说:记录抛出的接口异常是一种好习惯吗?是否存在普遍认可的最佳实践?我觉得这是一个不应该以任何方式包含在界面中的实现细节,但同时我觉得界面的用户应该拥有有价值的信息.
这样的评论是否是一个好的做法是另一个讨论的主题,所以为了限制这个问题的范围,我们假设我们已经同意用这样的评论来记录代码是一个好习惯.这里有'像这样的评论',我的意思是你可以从中产生一些东西,比如文档或元数据,而不仅仅是'正常'评论.示例包括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)
| 归档时间: |
|
| 查看次数: |
1579 次 |
| 最近记录: |