Page 794 - Introduction to Programming with Java: A Problem Solving Approach
P. 794
760 Appendix 5 Java Coding-Style Conventions Embedded Comments
1. Provide comments for code that might be confusing to someone reading your program for the first time. Assume the reader understands Java syntax.
2. Do not comment code that is obvious. For example, this comment is unnecessary and therefore exhibits poor style:
for (int i=0; i<10; i++)
// for loop header
3. Write your programs with clear, self-documenting code in order to reduce the need for comments. For example, use mnemonic (descriptive) identifier names.
4. Always include a single space between the // and the comment text.
5. The comment’s length determines its format.
• If the comment will occupy more than one line, use complete lines, like this:
// This is a block comment. Use it for comments that
// occupy more than one line. Note the alignment for /'s
// and words.
• If a comment is to reside on a line by itself, position it above the line of code it describes. Indent the // the same as tAhepdeascrgiboed linPe oDfFcode.EInncluhdeanblacnkelirne above the comment line. Here’s an example:
// Display error if invalid file name.
if (fileName == null || filename.getName().equals(""))
{
}
JOptionPane.showMessageDialog(this, fileErrorMsg);
• Manycommentsaresmallenoughtofitinspacetotherightofthecodetheydescribe.Whenever possible, all such comments should start in the same column, as far to the right as possible. The following example demonstrates proper positioning for short comments.
float testScores = new float[80]; // index is student number
int student;
...
while (testScores[student] >= 0) // negative index quits
{
testScores[student] = score;
...
6. Provideanendcommentforeachclosingbracethatisasignificantnumberoflines(fiveormore?)down fromitsmatchingopeningbrace.Forexample,notethe// end for rowand// end getSum comments below:
This comment just adds clutter.