Section 7.9.  Algorithmic Documentation

Table of Contents

7.9. Algorithmic Documentation

Use full-line comments to explain the algorithm.

Chapter 2 recommends coding in paragraphs. Part of that advice is to prefix each paragraph with a single-line comment.

That comment should explain at a high level what the associated paragraph contributes to the overall process implemented by the code. Ideally, if all the paragraph comments were to be extracted, they should summarize the algorithm by which the code performs its task.

Keep each such comment strictly to a single line. Any more than that interrupts the code excessively, making it harder to follow. If the paragraph is doing something too complicated to be explained in a single line, that is a sign that the code either needs to be split into several paragraphs, or else refactored out into a subroutine (which can then be given a more expansive block comment).

For example:

    sub addarray_internal {
        my ($var_name, $needs_quotemeta) = @_;

# Record original...
$raw .= $var_name;
# Build meta-quoting code, if required...
my $quotemeta = $needs_quotemeta ? 'map {quotemeta $_}' : $EMPTY_STR ;
# Expand elements of variable, conjoin with ORs...
my $perl5pat = qq{(??{join q{|}, $quotemeta \@{$var_name}})};
# Insert debugging code if requested...
my $type = length $quotemeta ? 'literal' : 'pattern'; debug_now("Adding $var_name (as $type)"); add_debug_mesg("Trying $var_name (as $type)");
# Add back-translation...
push @perl5pats, $perl5pat; return; }

Note, however, that the very first paragraphwhich will always be unpacking the subroutine's parameters (see Chapter 9)does not require a comment. Nor does the final return statement.

    Table of Contents
    © 2000- NIV