Search code examples
javanullpointerexceptionfinal

avoiding "Potential null pointer access"


which would you say is the best practice when implementing the following problem:

MyClass myVariable = null;
if ( ..condition 1.. ) {
  myVariable = new MyClass(1);
} else if ( ..condition 2.. ) {
  myVariable = new MyClass(2);
}

myVariable.execute();

Which would be a good solution to the warning?

  1. A finishing else

    final MyClass myVariable;
    ....
    } else {
      // let's say this assert makes sense here
      Assert.fail("This should not happen");
    }
    
  2. throw RuntimeException

    final MyClass myVariable;
    ....
    } else {
      throw new RuntimeException("Some message, like <should not happen>");
    }
    
  3. Check for NPE

    final MyClass myVariable;
    ....
    if (myVariable != null) {
      myVariable.execute();
    }
    
  4. Other ideas?

Thanks in advance!


Solution

  • It depends on whether either condition 1 or condition 2 must always be true. If condition 2 is the exact opposite of condition 1, you can replace the else if ( ..condition 2.. ) with else and solve your problem.

    If it's not, and the fact that both condition 1 and condition 2 are false indicates some invalid input, I'd throw an exception.

    If the scenario in which both conditions are false is a valid scenario, I'd check that myVariable is not null before calling myVariable.execute().