Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.java.programmer > #39795 > unrolled thread
| Started by | Wayne <wayne@nospam.invalid> |
|---|---|
| First post | 2022-07-26 20:36 -0400 |
| Last post | 2022-07-26 20:36 -0400 |
| Articles | 1 — 1 participant |
Back to article view | Back to comp.lang.java.programmer
What Makes for Good Comments? (Part 2 of 4) Wayne <wayne@nospam.invalid> - 2022-07-26 20:36 -0400
| From | Wayne <wayne@nospam.invalid> |
|---|---|
| Date | 2022-07-26 20:36 -0400 |
| Subject | What Makes for Good Comments? (Part 2 of 4) |
| Message-ID | <tbq1b6$29ngf$1@dont-email.me> |
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
Back to top | Article view | comp.lang.java.programmer
csiph-web