Self Documenting Code
A reader recently wrote asking if it's OK to skip commenting functions that are "obvious." He gave the example:
int32_t Integer_Sum(int16_t a, int16_t b);
I struggled to find any ambiguity in this definition and failed. It's pretty darn clear what the thing should do, and what the goesintos and goesoutas are. C's usual confusion over the size of an int has been resolved using POSIX-style typedefs. Versioning software tracks modifications.
His interesting point was that adding a comment header block simply results in more work - for instance, in maintaining those comments - while adding no useful additional information.
Why add comments to this very clear function definition?
First, this is a very contrived example. Few functions in the real world do so little or are so ineffably clear. I'd guess that such cases represent under a few percent of all of the code we write. So the cost to add a few comment lines almost isn't measurable. If the code is truly as simple as advertised, there will be no maintenance and hence the comments will incur no maintenance costs.
Second, never underestimate the power of developing and nurturing good habits. We always stop at red lights, even at 3 in the morning on lonely country roads. We always use our turn signals. Making exceptions starts the descent into poor habits. Pretty soon one routinely careens across 4 lanes of traffic without signaling.
I'm convinced most lousy drivers are blissfully unaware of their transgressions, which result from the accumulation of years of bad habits. As professional developers we, too, must consciously reject shortcuts that will inevitably lead to similar sins.
Third, what's obvious to you may be completely opaque to another developer.
Fourth, without a comment header block nothing separates this function from the previous and next ones in the module. It's buried and gets lost. Header comments serve as both documentation and textual breaks. We're not allowed to use fancy fonts, bold type, or colors to denote distinct sections of code.
Finally, who decides what functions needs comments and which don't? Skip 'em, and you'll encourage time-consuming documentation debates with your colleagues.
Though lots of very clear code exists, truly self-documenting software is about as common as unicorns.
Jack G. Ganssle is a lecturer and consultant on embedded development issues. He conducts seminars on embedded systems and helps companies with their embedded challenges. Contact him at firstname.lastname@example.org. His website is www.ganssle.com.