8 Stay away from comments

 

This chapter covers

  • Understanding the danger of comments
  • Identifying comments that add value
  • Dealing with different types of comments

Comments are probably one of the most controversial topics in this book, so let’s start by clearing up which comments we are talking about. This chapter considers comments that are inside methods and not used by external tools, like Javadoc:

interface Color {
  /**
   * Method for converting a color to a hex string.
   * @returns a 6 digit hex number prefixed with hashtag
   */
  toHex(): string;
}

Although controversial to some, my opinion aligns almost perfectly with those expressed by many brilliant programmers. Comments are an art form, but unfortunately, not many programmers study how to write good comments. Consequently, they end up writing only poor comments, which devalues the code. Therefore, as a general rule, I recommend avoiding them. Rob Pike presented similar arguments back in 1989 in his series of essays, “Notes on Programming in C”:

[Comments are] a delicate matter, requiring taste and judgment. I tend to err on the side of eliminating comments, for several reasons. First, if the code is clear, and uses good type names and variable names, it should explain itself. Second, comments aren’t checked by the compiler, so there is no guarantee they’re right, especially after the code is modified. A misleading comment can be very confusing. Third, the issue of typography: comments clutter code.

—Rob Pike

8.1 Deleting outdated comments

8.2 Deleting commented-out code

8.3 Deleting trivial comments

8.4 Transforming comments into method names

8.4.1 Using comments for planning

8.5 Keeping invariant-documenting comments

8.5.1 Invariants in the process

Summary