Java Reference
In-Depth Information
1.4
Program Style
In matters of grave importance,
style, not sincerity, is the vital thing.
OSCAR WILDE, The Importance of Being Earnest
Java programming style is similar to that used in other languages. The goal is to make
your code easy to read and easy to modify. This section gives some basic points on
good programming style in general and some information on the conventions nor-
mally followed by Java programmers.
Naming Constants
There are two problems with numbers in a computer program. The first is that they
carry no mnemonic value. For example, when the number 10 is encountered in a
program, it gives no hint of its significance. If the program is a banking program, it
might be the number of branch offices or the number of teller windows at the main
office. To understand the program, you need to know the significance of each con-
stant. The second problem is that when a program needs to have some numbers
changed, the changing tends to introduce errors. Suppose that 10 occurs 12 times in
a banking program, that 4 of the times it represents the number of branch offices,
and that 8 of the times it represents the number of teller windows at the main office.
When the bank opens a new branch and the program needs to be updated, there is a
good chance that some of the 10 's that should be changed to 11 will not be, or some
that should not be changed will be. The way to avoid these problems is to name each
number and use the name instead of the number within your program. For example,
a banking program might have two constants with the names BRANCH_COUNT and
WINDOW_COUNT . Both of these numbers might have a value of 10 , but when the bank
opens a new branch, all you need to do to update the program is to change the defi-
nition of BRANCH_COUNT .
One way to name a number is to initialize a variable to that number value, as in the
following example:
int BRANCH_COUNT = 10;
int WINDOW_COUNT = 10;
There is, however, one problem with this method of naming number constants: You
might inadvertently change the value of one of these variables. Java provides a way of
marking an initialized variable so that it cannot be changed. The syntax is
public static final Type Variable = Constant ;
Search WWH ::




Custom Search