什么是好注释呢?我们在写代码的时候,有些地方是一定要写注释的,这些地方的注释一定要尽可能的详细,并且无歧义。
比如在合作开发的时候,写的一些 API,这些 API 的函数的参数、返回值、以及函数的作用。例如 C# 中 System.Math.Max 函数:
/// <summary>
/// Returns the larger of two 32-bit signed integers.
/// </summary>
/// <param name="val1">The first of two 32-bit signed integers to compare.</param>
/// <param name="val2">The second of two 32-bit signed integers to compare.</param>
/// <returns>Parameter val1 or val2, whichever is larger.</returns>
public static int Max(int val1, int val2)
这些注释是非常好的注释,并且非常的详细。如果你写的代码将来也是要封装成 API 的,建议也要写的非常规范,以方便调用者使用。有返回值的,一定要详细解释好返回值的含义,比如:
/// <summary>
/// Indicates whether the specified Unicode character is categorized as a decimal digit.
/// </summary>
/// <param name="c">The Unicode character to evaluate.</param>
/// <returns>true if c is a decimal digit; otherwise, false.</returns>
public static bool IsDigit(Char c)
判断一个字节是否是十进制数字。我们注意看返回值的注释,详细写道,true
表示是一个十进制数字,否则返回 false
。工作中我见到过很多开发者写的类似返回 bool 值的方法的注释,都类似“是否是一个十进制数字”这样,这样就不是一个好注释,那么到底是 true
代表“是”还是 false
代表 “是” 呢?是不是容易混淆?
还有,再比如有些方法内的函数调用必须要有严格的调用顺序,这时候注释也是一定要加的,比如:
void Foo(){
F1();
F2();
// The function FN must be called in the last step
FN();
}
因为在后续功能扩展的时候,很有可能在其内部添加一些其他的函数调用,并且这个功能并不一定是当初开发这个函数的人继续扩展添加,如果调用顺序发生错误,很可能会出现很多麻烦。