If you followed programming course or if you just had talks with friends about documentation in the code, you most probably heard two voices:
Now I would like to shortly expose my personal feelings about that important question. They were built up mostly from ideas from Pad.
Here's a wonderful example (thx to Geoffrey Lee) of what I want to say:
// This is the include file #include <iostream.h> // This is the main function. int main() { // This is the statement saying "Hello world" and then goes to a new // line, using cout from iostream.h included earlier cout << "Hello world\n"; // This shows that we exit successfully return 0; } // end of file
Now look at the following code which has the same functionality:
#include <iostream.h> int main() { cout << "Hello world\n"; return 0; }
This is the first lesson to remember: documentation must be well targetted, e.g. you have to choose whether you want to document for beginners or experts (or in-between). Because the first example, documented for beginners, will be a pain for experts to read.
/* this function computes the next position given the speed and angle */ int compute_next_position(int speed, int angle)
The example function is said to be "self-documented". The documentation provided only pollutes the source code without bringing any valuable information.
This is the second lesson to remember: use self-documented code, e.g. you have to carefully choose good identification names for your functions, structures, global variables. And after all, if you're using a real editor such as Emacs, you won't type all the characters since you have completion. Generally speaking, local variables may have short names.
/* returns the new position */ void compute_next_position(int * pos, int speed, int angle)
Whooops.. for any reason, you changed the prototype of the function, but it was so trivial that you forgot to change documentation. This is the other bad side of documentation: it is not necessarily in sync with the actual code.
This is the third lesson to remember: the only up-to-date documentation is the code itself. Follows the famous extract from a great master: "Use the Source, Luke". Hopefully since we are in the free software world we are not stuck with sucking lagging documentation, we have the code.
Look at this code excerpt, here's an example of where documentation can be very nice:
fd = open(name, O_RDONLY); f = gzdopen(fd, "r"); .. gzclose(f); /* opened by gzdopen, but also closes the associated fd */
This documentation is very nice because if you're not an hyper-specialist of the zlib:
This is the fourth lesson to remember: documentation is only useful to bring information that is not immediately given by the code. Use it when you want to document a clever choice, a strange behaviour or a curious way of doing a thing.