Who, What, Where, When, How, and Why... But Mostly What and Why.
Descriptive Comments Make Code More Understandable
- When in doubt, it is generally better to err on the side of verbosity, it's easy to
rewrite or prune them (comments) later. It's difficult to try and recall your intentions 3-6 months (or even a week or two if you're me) after the fact.
- Code should be self-documenting to the extent possible, comments should provide additional information that's not obvious from the code itself.
- Well written comments mean developers don't have to make guesses or assumptions about code.
- Always, comment code that is non-obvious or
counter-intuitive that would trip up another programmer who is skimming the source code.
For example, if you have to do something weird to work around a bug with Perl 5.6.1 on Solaris servers running in the central time zone when there is a full moon, comment it!
#!/usr/bin/perl
package HashFromFile;
# Used for testing and debugging
use Object;
sub make {
my ($class, %args) = @_;
# The text file that provides the input for the hash we're going to create
my $file = $args{filename};
# Init the hash reference that will be populated with data read from $file
my $hash = {};
# Open readonly
open(FH, "< $file");
while (my $line = <FH>) {
# Skip over whitespace only lines
if ($line =~ /^\s+$/) {
next;
}
chomp($line);
# Split each line into a list by the ':' character, only the words
# around the first encountered ':' are used
my ($key, $value) = split(/:/, $line);
$hash->{$key} = $value;
}
close(FH);
return $hash;
}
1;