Java Reference
In-Depth Information
Place a local-variable declaration as close as possible to the first
use of the variable.
To illustrate this convention, consider the method in Fig. 13.10, which uses
this class Triple :
public class Triple {
int x; int y; int z;
Method permute permutes the components of its parameter w so that they are in
a particular order. It uses three local variables, which are declared at the begin-
ning of the method. The reader is forced to look at these variables even though
they may be of no interest. For example, the reader may be satisfied with look-
ing just at the two statement-comments. The placement of these local variables
cries out for explanatory comments for them.
In Fig. 13.11, the declarations of these variables have been placed as close
to their first use as possible. Now, the reader has to read them only when look-
ing at the implement of the statement comments. Further, their use is obvious,
and no comment is needed.
There may be valid reasons for placing a declaration of a local variable at
the beginning of the method body. Here is one. Suppose we replace all three vari-
ables by a single local variable tmp and use tmp to make all three swaps. Variable
tmp would be declared at the beginning of the method, perhaps like this:
int tmp; // Used in swapping variables
/** Permute w.x, w.y, w.z so that w.x <= w.y < w.z */
public static permute(Triple w) {
// Swap the largest of w.x, w.y, w.z into w.z
if (w.x > w.z)
{ int tmp1= w.x; w.x= w.z; w.z= tmp1; }
if (w.y > w.z)
{ int tmp2= w.x; w.x= w.z; w.z= tmp2; }
// Swap the larger of w.x and w.y into w.y;
if (w.x. > w.y)
{ int tmp3= w.x; w.x= w.y; w.y= tmp3; }
Figure 13.11
Putting local variables close to their use
Search WWH ::

Custom Search