Self-documenting code is a myth

Since my first programming assignment, I’ve always been hard-pressed to write self-documenting code. “Good code doesn’t need comments”, said my first teacher. He had a point: good code is self-explanatory, but there’s one thing even the most readable code cannot do: summarize itself.

I had the chance to be hired at a company where code quality was taken very seriously. Yet, developers relied on code readability and almost entirely avoided comments unless hacks were involved. Although the product was fairly easy to understand, it took me a few days to parse its structure because I had to read parse every a few lines out of every code block to understand what it did. All it would have taken was a few one-line comments describing the purpose of each block in plain english, and it would have made my job much easier. This code probably had to be re-read and re-understood a few dozen times since it was first typed, and a minimal effort would have changed everything.

Even when I edit my own code after a long break, I need some time to “get back into it” before I know the purpose of each block of code from memory. I’ve made an habit of leaving a simple comment every 5-10 lines of code and it changes everything. These are not very specific comments; they just tell what the block does, just like in those programming tutorials targetted at beginners. Even if I perfectly understand the purpose of each statement, single-line summaries save me from relearning it everytime I return to it.

This is even more crucial when you are sharing your code with strangers who will scan your code briefly looking for a very precise block, or with novice programmers. Hell, it’s just good practice!

Leave a Reply

Your email address will not be published. Required fields are marked *

To create code blocks or other preformatted text, indent by four spaces:

    This will be displayed in a monospaced font. The first four 
    spaces will be stripped off, but all other whitespace
    will be preserved.
    
    Markdown is turned off in code blocks:
     [This is not a link](http://example.com)

To create not a block, but an inline code span, use backticks:

Here is some inline `code`.

For more help see http://daringfireball.net/projects/markdown/syntax