This page contains a collection of suggestions for what to think about when writing code-level documentation. The documentation in code falls into two categories, described in separate sections below.
Interface documentation consists of the header comments for files, classes, and methods. Its purpose is to support abstraction: the creation of reusable modules with simple interfaces that hide complex internals. It should be much easier to use a module than to understand its implementation. The module's documentation describes its interface.
flushBuffer
don't say "Flush the buffer" in the documentation, since that provides no new information. Instead, say something different like "Write the buffer contents to the underlying network connection". This second form also indicates when someone might want to call this method.These comments are intended to help developers understand how code works internally. It includes documentation in the bodies of methods plus documentation of member variables in classes, which are usually private.
Don't repeat what is obvious from the code. Believe it or not, code like the following happens a lot:
// Increment i i++; |
Document things that are not obvious from the code, perhaps at a higher level. For example, you might include a short comment before each loop that indicates what each iteration of the loop corresponds to, and, at a high level, what each iteration does:
// Each iteration of the following loop processes one page, writing it // to swapping store if it is dirty. for {...} { ... } |
The following suggestions apply to both implementation and interface documentation.
Ideally, even private methods should provide encapsulation in the sense of hiding some nasty detail from the rest of the class. In this case, they should be documented in a fashion similar to public methods to reflect this abstraction.
On the other other hand, there will be some cases where there isn't much abstraction in a private method; it's just a way of sharing code between other methods. In this case the private method is just a shared implementation detail, so it's okay for the method header to be somewhat more abbreviated, for example:
This method is used internally in several places to perform the main body of work in copying data out of a Buffer. |
Even in this case parameters and result should be documented (but if it's hard to explain them outside the context of the calling method it's okay to keep the documentation brief and vague).
This second case as a necessary evil that we tolerate in situations where it's the best available alternative, but it's better if private methods can fall into the first category where they really have abstraction and the documentation reflects it.