University of the West of England, Bristol

Department of Computer Science and Creative Technologies


Netbeans Worksheet 7 - Layout and Comments


Learning Aims

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:


Theory Section (Part 1)

Free-Form Language

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:

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"
);}}

Practical Section (Part 1)

  1. Use Netbeans to create a new Java Tool project named BadLayout. Be sure to change the name of the main class to badlayout.BadLayout (as in previous worksheets).
  2. Type in the complete BadLayout program that appears above.

    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:

  3. Build the program and get it running. If you have typed it in exactly as shown above then it won't contain any errors (honestly!).

    The program should produce the following output:

    Bad Layout Program Runs Ok
    
  4. Try putting one space between all the words and punctuation characters in the program. For example, modify the System.out.println statement so it looks like this:
    System . out . println ( "Bad Layout Program Runs Ok" ) ;

    Build and run the program again.

  5. Try putting extra spaces inside the quotation marks and run the program. Note that this time the extra spaces are actually printed out.
  6. Try putting a new line inside the quotation marks, so that the message now looks like this:
    "Bad Layout Program
    Runs Ok"

    Note that this time your program won't compile.

  7. Remove the new line so that the quoted string once again starts and ends on the same line. Build and run the program to make sure it still works.
  8. Try removing the space between two words, such as 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.

  9. 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.


Theory Section (Part 2)

Rules for Pretty Layout

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.

The most important rules are:

The One Statement Per Line Rule

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...


The Indentation Rule

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.


The Consistent Punctuation Rule

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:

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.

Practical Section (Part 2)

  1. Create a new Netbeans project called LayoutTrier
  2. Use cut-and-paste (⌘C ⌘V) to copy the following program into the editor:
  3. 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++;}}}
    
  4. Build this program. Provided you have copied it correctly into the editor then there will be no compilation errors.
  5. Run the program and see what it does. Hint: When the program prompts for your name, click the mouse in the Output pane (beneath the editor), type your name and press Return.
  6. Use ctrl-shift-F to reformat the program.
    If we look carefully we'll see that Netbeans hasn't implemented the rule of putting one space before an open parenthesis, as in this example:
     System.out.printf("Your name has %d letters%n", nameLength);
    
        

  7. We can adjust Netbeans Preferences to suit our own personal formatting tastes. From the menu, select Netbeans > Preferences...
  8. When the preferences window pops up, select Editor, then Formatting.
  9. Change the Language setting to Java and the Category to Spaces.
  10. Select the options as indicated in the following image:
  11. Change the Category setting to Alignment.
  12. In the New Lines section of the window, select "else", "while", "catch" and "finally":

    When you've made these changes, click on OK.

  13. Use ctrl-shift-F to reformat the program.
  14. Build and run the program again just to be sure that it still does the same thing.
  15. Explore the other formatting options offered by Netbeans. Decide which ones you like and make your selections accordingly.

Theory Section (Part 3)

Commenting Close Braces

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:

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!

Practical Section (Part 3)

  1. Modify LayoutTrier to add the comments shown above next to each closing brace.
  2. Run the program again to make sure that it still works.

Theory Section (Part 4)

The javadoc Utility

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.

Special Markers in javadoc Comments

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;
   }

Commenting the Start of a Program

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:

  1. Comments should be written as grammatically correct English sentences.
  2. The words in the comment should be spelled correctly. Don't use text abbreviations!
  3. Each sentence in the comment should contain a verb!
  4. Normally, each sentence should start with a capital letter and end with a full stop, although the full stop can omitted from the end of the final sentence of the comment.
  5. Assume that the reader is a professional programmer who understands the Java language intimately.

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.

Practical Section (Part 4)

  1. Put a suitable javadoc comment at the start of the LayoutTrier program.
    Make sure that you place this immediately before the public class line and after any import lines.
  2. Build and run the program.
  3. Have a look at the suggested comment at the end of this worksheet and decide whether yours is better or worse than this one. Decide why you think it's better or worse.

Theory Section (Part 5)

Commenting the main () method Declaration

As 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!

Commenting the Individual Statements

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:

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:

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.

Commenting the while Loop

An 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) {

Commenting the Statements inside the while

The 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.

Practical Section (Part 5)

  1. Modify the LayoutTrier program to include suitable comments.
  2. Build this program and make sure it still works

Theory Section (Part 6)

Using Netbeans to run javadoc

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.

Netbeans has a built in menu command which will automatically create a javadoc page and display it. When we use this option, the HTML files are generated within the dist folder inside the Netbeans project. We can then copy this folder to a different place if necessary. Note that performing a clean (or clean and build) clears out any generated HTML files.

Practical Section (Part 6)

  1. From the Netbeans menu, select Run > Generate Javadoc
  2. After a few seconds, a Safari window opens showing the generated HTML file(s).
  3. Check the window and note the places where your comments are directly inserted into the HTML. It may be necessary to revisit the javadoc comments and re-run Generate Javadoc several times before we're happy with the final result.

Theory Section (Part 7)

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.

Commenting The Fields

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

Commenting the Methods

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.

Practical Section (Part 7)

  1. Open the CarTest project which you created in worksheet 6.
  2. Modify the Car class so that all the attributes, methods and statements have been commented.
  3. Use Netbeans's formatting commands to make sure that the class is correctly laid out.
  4. Build the CarTest project and make sure that it runs correctly.
  5. Generate Javadoc for the project, and make sure that you're happy with the generated pages.

What You Did - and What You've Learned

In this worksheet, you performed the following steps:

You have learned the following information about Java:

You learned about the javadoc utility:


Example javadoc comment for the LayoutTrier 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
 */

Return to home page