Previous Page
Next Page

7.11. Defensive Documentation

Comment anything that has puzzled or tricked you.

The final line in the previous example demonstrates the use of an in-line comment to overcome a maintainer's personal stumbling block:


    $build_mode = oct $arg{mode};   
# *From* octal, not *to* octal

Many programmers mistakenly assume that the oct builtin returns the octal version of its argument, when it actually converts its argument from an octal representation to decimal. That comment may have been added when the code was originally written (presumably in a d'oh! moment after several hours of fruitless debugging), or it may have been appended by a subsequent maintainer (to immortalize their own Homeric realization). Either way, by commenting it explicitly, that same false expectation will thereafter be averted every time someone new reads the code.

An in-line comment is appropriate whenever you encounter a subtle bug, or whenever you write some subtle code. "Subtle" has a very precise definition here: it means that you either had to look something up in a manual, or had to spend more than five seconds thinking about it before you understood its syntax or semantics.

For example, this:

    @options = map +{ $_ => 1 }, @flags;

needs to be commented:

    @options = map +{ $_ => 1 }, @flags;    # Anon hash ctor, not map block!

In general, if it puzzled or tricked you once, it will puzzle or trick youor whoever comes after youagain. To avoid that, leave a Hyre Be Dragones comment in the code.

    Previous Page
    Next Page