This worksheet we'll look at how to adjust the layout of your program to make it easier to read and understand. We'll also look at how to add comments to your program so that another person can look at your program and see how it works. Finally, we will look at using the javadoc tool to produce on-line documentation for your classes.
When you've completed this worksheet, you should be able to:
Jave is a free-form language. This means that with one or two minor exceptions it doesn't really matter where you put spaces, new lines, blank lines in your Java program.
The exceptions mentioned above are pretty obvious and easy to remember. The first two are to do with quoted strings:
System.out.println ("This message must not
be broken into two lines"); System.out.println ("These spaces will
be printed"); publicclassFred pub lic // is treated as a comment. For example:int count; // Count the number of attempts So applying these rules, it is possible to lay out the simple HelloWorld program like this:
package badlayout;
public class BadLayout{public static
void main(String[
]args)
{System.out.
println("Bad Layout Program Runs Ok"
);}}
Note that if you're looking at this page right now using the Safari web browser then you can avoid typing the whole thing by doing the following:
The program should produce the following output:
Bad Layout Program Runs Ok
System.out.println statement so it looks like this:System . out . println ( "Bad Layout Program Runs Ok" ) ;
Build and run the program again.
"Bad Layout Program
Runs Ok"
Note that this time your program won't compile.
public and class.
What happens when you try to build the program?
Replace the space(s) that you took out between the words. Recompile the program and make sure it still works.
Click the mouse within the editor window and type ctrl-shift-F
Instantly, Netbeans reformats the whole program so that it's nicely laid out and easy
to read. This is an example of how a modern program development system can save time
and increase productivity.
Although free-form layout sounds nice in theory, in practice it can make your programs pretty unreadable.
Programmers have been using free-form programming languages for over 30 years and, during that time, they have established a number of rules (or conventions) for laying out programs. These rules are designed to make programs easy to read. They work particularly well with large programs, but even so you should get into the habit of applying them to everything you do.
A professional programmer (and any one with aspirations to be a professional programmer) will always follow these layout rules.
All the programs in the lecture notes and worksheets follow these rules. Any program you see in a text book will usually follow them, too.
} should go on a line by itself. { on line by itself,
too. Bad Example:
public someMethod () {a = 5;daisy.mooo ();System.out.println ();}
In this example, the programmer has written a complete method on a single line (perhaps to save paper when printed). This might look ok in single isolated case or a small program, but it makes large programs much more difficult to understand
Good Example:
public someMethod () {
a = 5;
daisy.mooo ();
System.out.println ();
}
Here, the programmer has put each statement on a line by itself. This makes the code clear and it looks neater, too. Note that we've also applied the next rule to this example...
{ } should be indented by four
spaces. {
} Bad Example:
1. public class NotIndented {
2. public static void main (String [] args) {
3. int a = 5;
4. a = a * 10;
5. System.out.println (a);
6. }
7. }
This program does not follow the indentation rule. Each line starts at the left hand side of the page. As it's a small program, you can still understand it. If it was a large program, then it would be less easy to understand.
Good Example:
1. public class NotIndented {
2. public static void main (String [] args) {
3. int a = 5;
4. a = a * 10;
5. System.out.println (a);
6. }
7. }
This program has been indented according to the indentation rule. Lines 2 and 6 occur inside one pair of braces, and so they have been shifted (indented) by four spaces. Lines 3, 4 and 5 occurs inside a second pair of braces so they are indented by a further four spaces (making eight altogether).
Notice how lines 1 and 7 begin in the same column; as do lines 2 and 6. In both cases, there are matching opening and closing braces.
As a result of the indentation, the statements inside the main () method seem
to "leap out" at the reader.
Over the centuries, English writing has built up a number of conventions concerning the spacing around commas, semicolons, brackets and braces.
Adapting and applying these conventions to Java gives a nice consistent feel to your programs and makes them easy to read.
The rules can be summarized in this table:
{ |
One space before | New line after |
} |
Put on a line by itself | |
; |
No spaces before | New line after |
, |
No spaces before | One space after (or sometimes a new line after) |
. |
No spaces before or after | |
< = > |
Put a space on both sides | |
<= >= |
Put a space on both sides | |
( |
One space before * | No spaces after |
) |
No spaces before | One space after |
[ |
No spaces before | No spaces after |
] |
No spaces before | One space after |
* Not all programmers agree with putting one space before an open parenthesis, although we think it looks neat! Fortunately, you can set up Netbeans to match your own personal choice.
Bad Example:
public static void main(String[]args){
Adder sid=new Adder();
sid.add(3.6,5.0);
sid.add(5.3,18.2);
sid.add(17.0,-10.0);
}
In this example, the programmer has followed the One Statement Per Line Rule and the Indentation Rule, but has not paid any attention to the spacing of punctuation characters. As a consequence, all the lines have a cramped look and it is less easy to make out the characters, especially as it does not conform to the expectations of the English reader.
Although this does not seriously detract from the readability of the program, a little bit of effort can make it look much better...
Good Example:
public static void main (String [] args){
Adder sid = new Adder ();
sid.add (3.6, 5.0);
sid.add (5.3, 18.2);
sid.add (17.0, -10.0);
}
This is the same code, rewritten so that it follows the punctuation spacing rules. It is less cramped, easier on the eye and so less tiring to read and understand.
package layouttrier;import java.util.*;public class LayoutTrier
{ public static void main(String
[] args)
{
int nameLength, i;
char ch;
Scanner in=new Scanner(System.in);
System.out.print ("Please enter your name:"); String name=in.nextLine(
);
nameLength=name.length ();
System.out.printf("Your name has %d letters%n", nameLength) ;
i=0; while(i < nameLength){ch=name.charAt(i);
System.out.printf ("Character %d is %c %n", i+1, ch);i++;}}}
System.out.printf("Your name has %d letters%n", nameLength);

When you've made these changes, click on OK.
Each open brace requires a matching close brace, and we've already established that the close brace should go on a line itself. However, looking again at the previous example, it finishes with these three lines:
} } }
Even if you've lined up these closing braces with the corresponding open braces, it can still be a bit tricky to decide which open is matching with which close.
A simple way around this problem is to put a short comment after every close brace:
while statement - hence
we should write it as } // while main () method - hence we
write } // main () } // LayoutTrier Putting all this together, we should rewrite these final three closing braces like this:
} // while } // main () } // LayoutTrier
We recommend this a good practice, but it is fair to say that there are plenty of programmers who don't bother!
A standard part of the Java system is a utility program called javadoc. This program reads a java program, extracts some of the comments in the program, and uses them to build a web page. This web page becomes the on-line documentation for the program.
javadoc only recognizes comments if they take this form:
/** * The actual text of the comment goes here */
It is important to remember that a javadoc comment starts with a slash and TWO stars,
but it only needs ONE star and a slash to finish it. Note that Netbeans automatically puts
a * at the beginning of each line. These stars are not actually part of the
comment.
javadoc expects each comment to be placed immediately before the line containing the class or method declaration.
javadoc recognizes a number of special markers in a comment and treats them in a
special way. All of these markers begin with an @ sign.
The commonest marker is probably @author followed by the name of the person
who wrote the class. It's used like this:
/** * This is the comment to describe the program or class * @author John Smith */
Another common marker is used to describe each paramter of a method. It usually takes this form:
* @param parameterName This is a description of the parameter
For example:
/**
* Change the gear
* @param gear The required value for the gear
*/
public void setGear (int gear) {
this.gear = gear;
}
If you were to present another person with your version of LayoutTrier, then that person would have no idea what the program does. It would be really helpful if you were to write a comment at the start of the program explaining what it does. Furthermore, if that comment were in javadoc form, then you could create a web page and have instant on-line documentation for the program.
From the previous section, we saw that a javadoc comment must begin with /** and
must be placed immediately before the public class line.
Putting all this together, the first few lines of LayoutTrier should look like this:
import uwejava.*;
/**
* Comment to describe the class
* @author A Student
*/
public class LayoutTrier {
Question: Why has the comment not been placed as the very first line of the file?
Why has it been placed just after the import line?
Many students have difficulty actually writing comments so here are some general rules:
A further difficulty encountered by many students is knowing exactly what to write. They either go into too much detail, or too little detail, or an inappropriate mixture of both! They don't know what's important and what isn't and so the emphasis of the comment is wrong. A typical mistake is to restate the code in English but to be really useful, comments should just state what the program does, but not how it does it! We'll be returning to this later on in this worksheet.
public class line and
after any import lines. main () method DeclarationAs a matter of form, we should put a javadoc comment before the main () method.
However, as we've already described what the program does in the comment for the class, there's
really very little more to add so we should just acknowledge that the main method exists
with a simple comment like this. Note that Netbeans automatically includes an @param marker
for the args parameter. This can safely be removed in this instance:
/**
* The main method for this program
*/
public static void main (String [] args) {
You might think that this is fairly pointless, but by putting in this comment it shows that there really is nothing more to say. If we had left out this comment then another programmer might wonder what we had forgotten to write!
Although the main () method declaration only requires a trivial javadoc comment,
the statements within main () need explanation. Of course, this
brings us back to the student's dilemma: what to say and in what detail...
Looking at the code in the main () method what do we see? Looking at the broad features, we can see it does the following:
Scanner object. Given this description, a professional programmer would have no difficulty in either understanding how the program works, and could even recreate it from scratch if necessary. All that's necessary is to create suitable comments and place them in the program.
Making a start, we get something like this:
// Declare all local variables
int nameLength, i;
char ch;
// Create object to accept user input
Scanner in=new Scanner (System.in);
// Get the user's name
System.out.print ("Please enter your name:");
String name=in.nextLine ();
// Find the length of the name
nameLength=name.length ();
// Print name length message to user
System.out.printf ("Your name has %d letters%n", nameLength);
We should note the following:
// form of comment (not javadoc comments) You might think that some of the comments are unnecessary as the code they describe is obvious. You might be right (there is no right or wrong here), but by putting in a comment you are making it clear that there is nothing more to be said. We (the teachers) are of the opinion that all statements in a method should be covered by a comment - even if the comment is pretty trivial. That way, you're making it clear that there's nothing hidden that you just couldn't be bothered to describe. From the above example, you can see that one comment can cover more than one statement.
while LoopAn experienced programmer would immediately recognize that the two statements
i = 0;
while (i < nameLength) {
are setting up a loop which will run once for every character in the user's name. This statement
therefore needs a comment.
We should also put a comment just before the while statement. Perhaps something like this:
// Set up for the start of the while loop
i = 0;
// Loop through every character in the user's name
while (i < nameLength) {
Actually, many programmers would decide that the two statements belong together and that only one comment is needed for both of them:
// Loop through every character in the user's name
i = 0;
while (i < nameLength) {
whileThe statements inside the while should be commented, too:
// Loop through every character in the user's name
i = 0;
while (i < nameLength) {
// Get the next character from the user's name
ch = name.charAt (i);
// Write message to user
System.out.printf ("Character %d is %c %n", i + 1, ch);
// Advance to the next character
i++;
} // while
Note that we are still following the same rules for commenting and layout that we discussed earlier in this worksheet.
We will now see how we can use Netbeans to run javadoc to produce on-line documentation for our programs.
Javadoc is normally run as a command line program within OS X Terminal, using this command:
javadoc *.java
This command processes all files whose names end with .java and produces an
equivaent HTML file for each one. Additionally, javadoc also produces an index file, called index.html (of
course), which we can use to access all the other files.
Let's return to the Car class that you created in worksheet 6 and see how we might add comments it.
We suggest that you look back at your version of Car.java (part of the CarTest project) before continuing. Remind yourself which are the attributes and which are the methods within this class.
The Car class has three fields, thus:
String make; String model; int gear;
Unlike all the other comments we've previously seen, we suggest that for fields it is better to place comments beside them
For example, we could say:
String make; // Manufacturer of the car String model; // Model name of the car int gear; // Which gear the car is in
The first method in the Car class is the constructor, which is also called Car
We should put a javadoc comment before this method declaration and put normal comments for the statements inside:
/**
* Construct a car with the specified make and model name.
* A new car is always created in neutral gear.
* @param make The make/manufacturer of the new car
* @param model The model name of the new car
*/
public Car (String make, String model) {
// Save the car's make and model
this.make = make;
this.model = model;
// Set gear to neutral
gear = 0;
} // Car
Continuing with the setGear () method we might say:
/**
* Put the car into the specified gear.
* @param gear The required gear. Note that the gear is not checked to see if it is valid.
*/
public void setGear (int gear) {
// Put the car into the required gear
this.gear = gear;
} // setGear ()
Of course, we should continue until all the methods have been commented.
In this worksheet, you performed the following steps:
You have learned the following information about Java:
You learned about the javadoc utility:
/** and end with */ @author and @param markers which
are treated in a special way by the program. /** * This program prompts the user to enter a name (or any string). * It counts the number of characters in the string and writes this * out as a message. * It then outputs each character in turn in a separate message. * @author A Student */