godoc
是包的文档,所以应该始终为包中声明的每个公共符号 — 变量、常量、函数以及方法添加注释。
以下是 Google Style
指南中的两条规则:
- 任何既不明显也不简短的公共功能必须予以注释。
- 无论长度或复杂程度如何,对库中的任何函数都必须进行注释
`
golang
package ioutil
// ReadAll reads from r until an error or EOF and returns the data it read.
// A successful call returns err == nil, not err == EOF. Because ReadAll is
// defined to read from src until EOF, it does not treat an EOF from Read
// as an error to be reported.
func ReadAll(r io.Reader) ([]byte, error)
这条规则有一个例外; 您不需要注释实现接口的方法。 具体不要像下面这样做:
```golang
// Read implements the io.Reader interface
func (r *FileReader) Read(buf []byte) (int, error)
这个注释什么也没说。 它没有告诉你这个方法做了什么,更糟糕是它告诉你去看其他地方的文档。 在这种情况下,我建议完全删除该注释。
这是 io
包中的一个例子
// LimitReader returns a Reader that reads from r
// but stops with EOF after n bytes.
// The underlying implementation is a *LimitedReader.
func LimitReader(r Reader, n int64) Reader { return &LimitedReader{r, n} }
// A LimitedReader reads from R but limits the amount of
// data returned to just N bytes. Each call to Read
// updates N to reflect the new amount remaining.
// Read returns EOF when N <= 0 or when the underlying R returns EOF.
type LimitedReader struct {
R Reader // underlying reader
N int64 // max bytes remaining
}
func (l *LimitedReader) Read(p []byte) (n int, err error) {
if l.N <= 0 {
return 0, EOF
}
if int64(len(p)) > l.N {
p = p[0:l.N]
}
n, err = l.R.Read(p)
l.N -= int64(n)
return
}
请注意,LimitedReader
的声明就在使用它的函数之前,而 LimitedReader.Read
的声明遵循 LimitedReader
本身的声明。 尽管 LimitedReader.Read
本身没有文档,但它清楚地表明它是 io.Reader
的一个实现。
贴士:
在编写函数之前,请编写描述函数的注释。 如果你发现很难写出注释,那么这就表明你将要编写的代码很难理解。
不要注释不好的代码,将它重写
Don’t comment bad code — rewrite it
— Brian Kernighan
粗劣的代码的注释高亮显示是不够的。 如果你遇到其中一条注释,则应提出问题,以提醒您稍后重构。 只要技术债务数额已知,它是可以忍受的。
标准库中的惯例是注意到它的人用 TODO(username)
的样式来注释。
// TODO(dfc) this is O(N^2), find a faster way to do this.
注释 username
不是该人承诺要解决该问题,但在解决问题时他们可能是最好的人选。 其他项目使用 TODO
与日期或问题编号来注释。
与其注释一段代码,不如重构它
Good code is its own best documentation. As you’re about to add a comment, ask yourself, ‘How can I improve the code so that this comment isn’t needed?’ Improve the code and then document it to make it even clearer.
好的代码是最好的文档。 在即将添加注释时,请问下自己,“如何改进代码以便不需要此注释?’ 改进代码使其更清晰。
— Steve McConnell
函数应该只做一件事。 如果你发现自己在注释一段与函数的其余部分无关的代码,请考虑将其提取到它自己的函数中。
除了更容易理解之外,较小的函数更易于隔离测试,将代码隔离到函数中,其名称可能是所需的所有文档。