Comments


Comments are parts of source code that the compiler ignores: they have no effect on the program to the computer. A lot of programmers would see any comment and consider them failures because good code "self-documenting." Unfortunately, as John Ousterhout points out in A Philosophy of Software Design, the code interface includes informal aspects that cannot be expressed in the programming language. It is true that writing code to be as self-documenting as possible is a good idea, but it is an unattainable ideal for all but the smallest units of code. Since the program itself is the only documentation guaranteed to be up to date, of course code should be written to be as readable as possible: the best way to design good code is for it be simple. Even so, there are times when the only way to make the code clearer is comments. Comments should be used describe why something is the way it is, not what which is what the code describes. Comments can be used to provide literate API documentation extracted from source code by following some conventions in the language (the tool for doing this in Ruby is RDoc).

See this example from the Anki Record gem which uses basic RDoc conventions:

module ChecksumHelper
  ##
  # Returns the integer representation of the first 8 characters of the SHA-1 digest of the +sfld+ argument
  def checksum(sfld)
    Digest::SHA1.hexdigest(sfld)[0...8].to_i(16).to_s
  end
end
Previous Next