What Makes for Good Comments? (Part 2 of 4)

5 views
Skip to first unread message

Wayne

unread,
Jul 26, 2022, 8:37:08 PM7/26/22
to
Why Comments

Why comments refer to the reasons for writing the code in a particular way. A
why comment is for explaining a particular implementation decision or the
programmer’s intent, especially if it’s not the “obvious” design choice. If
the obvious choice is to use an int but you use a double or (even stranger) a
String, a why comment is useful.

There can be many reasons why some code was written in a non-obvious way. Some
examples include formulas that were rearranged to reduce round-off error or to
avoid overflow, code you are not allowed change, and code requiring
non-intuitive design for security reasons (say to eliminate side-channel
attacks). (A poor reason is trying for extra performance.)

Why comments are also used to document the reasons for the code, often listing
a reference to an issue (or ticket) in some issue-tracking system. Comments
for bug fixes generally go in the testing code, not the application code.
(When fixing bugs, you first add a failing test then fix the code. The bug fix
comment belongs with the test code.)

Here’s an example of a good why comment, adapted from Robert Martin’s Clean
Code (p. 59):

// The following trim is required, since it
// removes leading space that would cause the
// the item to be recognized as another list:
String listItemContent = match.group(3).trim();

(Some why comments are too long to mix with the code and can be kept in a
separate "design notes" text file.)

Feedback welcome!

--
Wayne


Reply all
Reply to author
Forward
0 new messages