Documentation and Programming Style

In this lesson, we will look at some guidelines for choosing Java identifiers, indenting Java statements, and writing comments.

Most programs are used many times and are changed either to fix bugs or to accommodate new demands by the user. If the program is not easy to read and to understand, it will not be easy to change. It might even be impossible to change without heroic efforts. Even if we use our program only once, we should pay some attention to its readability. After all, we will have to read the program to debug it.

In this appendix, we discuss three techniques that can help make our program more readable: meaningful names, indenting, and comments.

Naming Variables, methods, and classes

Names without meaning are almost never good. A variable name should suggest its use, a method name should describe its action, and a class name should represent its purpose. If the variable holds a tax rate, we might name it taxRate. A method that computes a tax might be named getTaxRate. And a class that defines methods for a town’s tax collector might be named Taxer.

In addition to choosing names that are meaningful and legal in Java, we should follow the normal practice of other programmers. That way it will be easier for them to read and combine our code with their code, should we work on a project with more than one person. By convention, the name of each variable and method begins with a lowercase letter, and each class name begins with an uppercase letter. If the name consists of more than one word, use a capital letter at the beginning of each word after the first one. For example, the variable numberOfTries and the class StringBuffer follow these conventions.

Use all uppercase letters for named constants to distinguish them from other variables. Use the underscore character to separate words, if necessary, as in INCHES_PER_FOOT.

Indenting

A program has a structure: Smaller parts are within larger parts. We use indentation to indicate this structure and thereby make our program easier to read. Although Java ignores any indentation we use, indenting consistently is essential to a good programming style.

Each class begins at the left margin and uses braces to enclose its definition. For example, we might write:

public class CircleCalculation
{
   .
   .
   .
} // End CircleCalculation

The data fields and methods appear indented within these braces, as illustrated in the following simple program:

Get hands-on with 1200+ tech skills courses.