11 ms·
What's missing IMO from those example comments (and most automatic documentation) is the "why". I can almost always look at the code to figure out that a functi
by variaga 5y ago
What's missing IMO from those example comments (and most automatic documentation) is the "why". I can almost always look at the code to figure out that a function takes a Foo and returns a Bar. What's almost never obvious from the code itself is "why would I want to convert a Foo to a Bar" or "under what circumstances should I use this function instead of something else".
E.g.
char* strncpy(char *dst, const char *src, size_t n)
and
size_t strlcpy(char *dst, const char *src, size_t size)
both copy a string from src to dst with a limit on the number of bytes copied. Good comments for would not simply explain what they do and what the arguments/returns represent, but under what circumstances to prefer each variant.
Going with the "6 W's":
"How" (does this code work) and "What" (does this code do) can mostly be explained by the code itself, although comments should be used to clarify anything non-obvious, for instance if you're depending on a side effect or something.
"Where" (should you use this code) and "why" (should you use this code) need to be covered by comments. It is extremely hard to figure those out from the code alone.
"Who" (wrote it) and "when" (was it written) should be in the version control system metadata. Putting those in comments is a good way to ensure the comments are out-of-date/wrong in any long-lived codebase.
- TeMPOraL 5y agoI mostly agree with what you wrote, but then take a look at the man pages for the two functions you mentioned: https://linux.die.net/man/3/strlcpy https://linux.die.net/man/3/strlcpy https://linux.die.net/man/3/strncpy https://linux.die.net/man/3/strncpy Note how most of the text there is focused on the "How" and "What", because both functions have a bunch of requirements for their arguments that are not expressed in their respective signatures. Some languages have better tools for expressing these requirements in code. But when they can't be expressed in a way that can be enforced by the compiler, IMO they absolutely need to be mentioned in an interface-level comment (i.e. above function signature), to give users a fighting chance of avoiding bugs. Also worth noting that the particular constraints around strncpy() and strlcpy() will not be obvious in the implementation either - the programmer trying to make use of these functions would have to study the implementation to notice potential issues. A well-placed comment can save them an expensive context switch here.