Java Reference
In-Depth Information
Clearly, the author of this program didn't think about the order in which the initialization of the
Cache class would take place. Unable to decide between eager and lazy initialization, the author
tried to do both, resulting in a big mess. Use either eager initialization or lazy initialization,
never both.
If the time and space cost to initialize a field is low or the field is required in every execution of the
program, eager initialization is appropriate. If the cost is high and the field might not be required in
some executions, lazy initialization may be preferable [EJ Item 48]. Also, lazy initialization may be
necessary to break a cycle in class or instance initialization ( Puzzle 51 ).
The Cache class could be repaired either by reordering the static initializations so the initialized
field was not reset to false after sum was initialized or by removing the explicit static initialization
of the initialized field. Although the resulting programs would work, they would still be
confusing and ill-structured. The Cache class should be rewritten to use eager initialization. The
resulting version is obviously correct and much simpler than the original. With this version of the
Cache class, the program prints 4950 as expected:
class Cache {
private static final int sum = computeSum();
private static int computeSum() {
int result = 0;
for (int i = 0; i < 100; i++)
result += i;
return result;
}
public static int getSum() {
return sum;
}
}
Note that we use a helper method to initialize sum . A helper method is generally preferable to a
static block, as it lets you name the computation. In the rare cases when you must use a static block
 
 
Search WWH ::




Custom Search