Programming and Problem Solving with Java

(やまだぃちぅ) #1

(^64) | Java Syntax and Semantics, Classes, and Objects


Beyond Minimalism: Adding Comments to Code


All you need to create a working application is the correct combination of declarations and
executable statements. The compiler ignores comments, but this kind of documentation is
of enormous help to anyone who must read the code. Comments can appear anywhere in
your code except in the middle of an identifier, a reserved word, or a literal constant.
Java comments come in two forms. The first is any sequence of characters enclosed by
the /* */pair. The compiler ignores anything within the pair. Here’s an example:

String idNumber; /* Identification number of the aircraft */

One special note about using this form of comment: When the first character of the
comment is an asterisk, the comment has a special meaning that indicates it should be
used by an automatic documentation generation program called javadoc. For the time being,
as we do not discuss javadoc in this text, we recommend that you avoid comments that
start with /**.
The second, and more common, form begins with two slashes (//) and extends to the end
of that line of the program:

String idNumber; // Identification number of the aircraft

The compiler ignores anything after the two slashes to the end of the line.
Writing fully commented code is good programming style. A comment should appear at
the beginning of an application or class to explain what it does:

// This application computes the weight and balance of a Beechcraft
// Starship–1 airplane, given the amount of fuel, number of
// passengers, and weight of luggage in fore and aft storage.
// It assumes that there are two pilots and a standard complement
// of equipment, and that passengers weigh 170 pounds each.

Another good place for comments is in field declarations, where comments can explain
how each identifier is used. In addition, they should introduce each major step in a long
code segment and should explain anything that is unusual or difficult to read (for example,
a lengthy formula).
You should keep your comments concise and arrange them in the code so that they are
easy to see and it is clear what they document. If comments are too long or crowd the state-
ments, they make the code more difficult to read—just the opposite of what you intended!
In this text we use color to make the comments stand out from the rest of the Java code in
our examples.

Output


Have you ever asked someone, “Do you know what time it is?”, only to have the person smile
smugly and say, “Yes, I do”? This situation is like the one that currently exists between you
Free download pdf