Java Reference
In-Depth Information
had been written before the method body was written, the problem of figuring
out what the method did and the resulting mistake in writing a call would not
have arisen.
Guideline 2. Define variables
Suppose you are asked whether variable x in the method of Fig. 13.1 is ini-
tialized correctly. You will probably reply with another question, “well, how is it
used, what is its meaning?” You are right to answer this way, and if you took this
idea further into your own programming, you would:
2. Write down the meaning of a variable before you use it.
This meaning should appear near the declaration of the variable, be it a static
variable, a nonstatic variable, or a local variable.
A student once told us that programming was easy; all you had to do was to:
Define your variables. Write the program to keep values consis-
tent with the definition while making progress in the calculation.
Many program errors are made by inconsistent use of variables, which is caused
by not writing down their definitions.
In the method of Fig. 13.1, variables x and i have to be defined together:
x is the number of primes in the range 2..i-1.
Guideline 3. Keep documentation and program consistent
Finally, do your best to keep documentation and program consistent. Here
are some examples.
If you decide to change what a method does:
3a. Change the method specification, then the method body.
public static int numberOfPrimes() {
int x= 1;
for ( int i= 3; i != 103; i= i + 1) {
boolean b= i > 1;
int k= 2;
while (b && k != i) {
if (i%k == 0)
{ b= false ; }
k= k + 1;
if (b)
{ x= x + 1; }
return x;
Figure 13.1:
Counting primes —with missing specifications and other comments
Search WWH ::

Custom Search