Java Reference
In-Depth Information
quotes, are easy to spot with an editor that distinguishes comments, strings,
identifiers, and keywords with visual clues such as color, font, and style.
After you choose a comment style, you have to decide how much to com-
ment. This topic is also debated in the Java community, and no clear answers
have emerged. Some purists argue that comments provide additional bug-
prone lines of code that are hard to keep in sync through maintenance. Others
argue for documenting everything profusely. Some in the middle ground opt
for commenting only type definitions and methods. I tend to fall between the
most extreme camps. As I stated earlier, we should describe why something is
done, not what is being done. Commenting should always add something,
and never take anything away. If a line of code is obvious, it needs no com-
ment. If intentions are not clear, the best course is to make them clear. The
next best alternative is to document the decision. For various reasons, includ-
ing conflicting priorities and unit testing, bugs may be discovered but not
fixed. These should always be documented.
In a self-published coding standard document, Scott Ambler offers the fol-
lowing example. This line of code has an unclear initialization:
int index = -1;
A comment makes it clear:
int index = -1; // -1 serves as flag meaning the index isn't valid
A constant also makes it clear, and makes the comment unnecessary:
static final int INVALID= -1;
int index = INVALID;
This example brings us to a critical documentation guideline: Some things
should not be commented. To keep comments with the described code in sync
and up to date takes effort. Comments are always used to assist programmers,
not programs. If a comment doesn't clarify or provides only redundant infor-
mation, remove it. In all cases, clear, concise code that does not need com-
ments is the best option.
In many cases, it helps to maintain a change history within a program. Some
change-control systems automatically append a change history as files are
checked in and out. In any case, a robust change history is an important tool
that can provide enormous assistance with these refactoring activities:
Removal of dead code. A change history can provide information about
the existence of dead code, called lava flow in the AntiPatterns book.
Search WWH ::

Custom Search