As an alternative to static blocks, Oracle docs are suggesting to call a method(s) and the example is using a variable assignment:
public static varType myVar = initializeClassVariable();
The advantage of private static methods is that they can be reused later if you need to reinitialize the class variable.
But if I don't need (and want to avoid unused) extra variable and also return statement in my static block, what is a better way to call static code?
Calling a static method in the constructor is wrong design for executing static code once (constructor can be private
for utility class) for static block
public MyClass() {
MyClass.initializeClassVariable();
}
So is the only improvement is reducing variable access level to private ?
private static varType myVar = initializeClassVariable();
Or a better approach is to keep static block and add the method there?
static {
initializeClassVariable();
}
The "alternative to static blocks" is about initializing a single static field.
Example:
class A {
static Map<String, Integer> romans;
static {
romans = new HashMap<>();
romans.put("I", 1);
romans.put("V", 5);
romans.put("X", 10);
}
}
Alternative:
class A {
static Map<String, Integer> romans = initRomans();
private static Map<String, Integer> initRomans() {
Map<String, Integer> r = new HashMap<>();
r.put("I", 1);
r.put("V", 5);
r.put("X", 10);
return r;
}
}
As the article says, with this code you can reset the static field.
public static void resetRomans() {
romans = initRomans();
}
If your code does something else, then the "alternative" isn't applicable, and you write the code in a static initializer block.
class A {
static {
Manager.register(A.class);
}
}