#975 – Guidelines for Commenting Your Code

The primary goal of including comments in your code is to make the code + comments self-documenting enough that a developer other than the original author can understand what the code does and how it does it.

Guidelines for well commented code include:

  • Wherever possible, the code should “self document”:
    • Meaningful names for variables and methods
    • Consistent layout
    • Modularized code — each method performs a single task
    • Minimize nesting, where possible
  • Write effective comments:
    • Don’t just repeat what the code does
    • Use a comment to summarize a block of code that follows the comment, providing a high-level description of what the code does
    • Describe what and why, rather than how.  The code describes how and sometimes what.  Comments add to the what and also talk about why.
    • Modify comments when you modify code, if appropriate (i.e. keep the comments current)
    • Don’t comment tricky code–rewrite the code
    • Write for humans