Java Reference
In-Depth Information
51 System.out.print("\\");
52 for ( int i = 1; i <= (SUB_HEIGHT line); i++) {
53 System.out.print(" ");
54 }
55 System.out.println("|");
56 }
57 }
58 }
Notice that the SUB_HEIGHT constant is declared with class-wide scope, rather
than locally in the individual methods. While localizing variables is a good idea, the
same is not true for constants. We localize variables to avoid potential interference,
but that argument doesn't hold for constants, since they are guaranteed not to change.
Another argument for using local variables is that it makes static methods more inde-
pendent. That argument has some merit when applied to constants, but not enough. It
is true that class constants introduce dependencies between methods, but often that is
what you want. For example, the three methods in DrawFigure2 should not be inde-
pendent of each other when it comes to the size of the figure. Each subfigure has to
use the same size constant. Imagine the potential disaster if each method had its own
SUB_HEIGHT , each with a different value—none of the pieces would fit together.
Further Variations
The solution we have arrived at may seem cumbersome, but it adapts more easily to a
new task than does our original program. For example, suppose that you want to gen-
erate the following output:
+----------+
|\......../|
| \....../ |
| \..../ |
| \../ |
| \/ |
| /\ |
| /..\ |
| /....\ |
| /......\ |
|/........\|
+----------+
| /\ |
| /..\ |
| /....\ |
| /......\ |
|/........\|
|\......../|
| \....../ |
| \..../ |
| \../ |
| \/ |
+----------+
 
Search WWH ::




Custom Search