Search code examples
javacompiler-errorsinitializationsonarqubesonarlint

Avoid uninitialized non final member class/ class variable


I found that prevent forgetting to initialize objects isn't fully covered in Java compiler and/or Sonar warning, I'm using latest Eclipse with latest Sonar plugin.

I'm missing error/warning about not initializing for example for Map (similarly can be String)

In the example Class Variable mapStatic and Member Variable map, both private and not final and can be declared without initialization and without any error/warning about the NullPointerException to come.

Although for local variables as mapVar I get compile error Compile The local variable mapVar may not have been initialized

Obviously Local variables are not assign with default value, but still why compiler/sonar doesn't warn about NullPointerException?

Local variables are slightly different; the compiler never assigns a default value to an uninitialized local variable.

private static Map<String, String> mapStatic; // Missing compile/warning
private Map<String, String> map; // Missing compile/warning
public void  put() {
    map.put("x", "1"); // NullPointerException
    //Map<String, String> mapVar;
    //mapVar.put("x", "1"); // Compile The local variable mapVar may not have been initialized
}
static {
    mapStatic.put("x", "1"); // NullPointerException        
}

Also if I add final I'll get compile error Compile The local variable map may not have been initialized.

I found an answer that it won't be in compile time, so how can avoid or found this issues beforehand?

Failing to initialise a value is a logic error on the part of the programmer, and should be caught as soon as possible. Java does this at compile time for locals, but only at runtime (or not at all) for fields.


Solution

  • The behavior you seem to be looking for is more likely to produce unnecessary warnings than to help the design.

    The fact that class-level fields get a JVM-assigned default value is by design, and it's OK for many reasons, including:

    • It's possible that the field's value won't be known until after object construction. This is typical, because many field values only get set in setters.
    • It's possible that the current class itself doesn't know what the value is. In this case, the responsibility to set the value is outside the class, so the warning would simply be an annoyance.
    • What if the field won't be used in the current class at all?

    This is the area where the responsibility lies with the developer. Only you know the order of execution, only you know what data the code depends on, and only you have the responsibility to test the code and ensure that it's bug-free.