Search code examples
javadead-code

Why is this code segment marked dead code?


For the life of me, I can't see why Eclipse is marking the else if clause below as "dead code":

BaType rbName = rSoapXml.getName().getBName();
BaType cbName = cSoapXml.getName().getBName();
IaType riName = rSoapXml.getName().getIName();
IaType ciName = cSoapXml.getName().getIName();

String rbNameF = rbName.getF() == null ? "null" : rbName.getF();
String cbNameF = (cbName == null || cbName.getF() == null) ? "null" : cbName.getF();
LOG.info("\n***BEFORE***: " + rbNameF + ", COM: " + cbNameF);

if (cbName != null) {
  if (riName != null) {
    String errMsg = "Expected an I message but received a B instead.";
    throw new RuntimeException(errMsg);               
  }
  if (cbName.getBorE() != null)
    rbName.setBorE(cbName.getBorE());
  if (rbName.getBorE() == null && cbName.getBorE() == null) {
    String errMsg = "Missing B name!";
    throw new RuntimeException(errMsg);               
  }
}
else if (ciName != null) {                                               // dead
  if (rbName != null) {                                                  // dead  
    String errMsg = "Expected a B message but received an I instead.";   // dead
    throw new RuntimeException(errMsg);                                  // dead
  }                                                                      // dead
  if (ciName.getIName() != null)                                         // dead
    riName.setIName(ciName.getIName());                                  // dead
  if (riName.getIName() == null && ciName.getIName() == null) {          // dead
    String errMsg = "Missing I name";                                    // dead
    throw new RuntimeException(errMsg);                                  // dead 
  }

}

Points I have considered:

  1. ciName is initialized at runtime and cannot be guaranteed to be non-null.
  2. cbName is not guaranteed to be non-null either, hence the else following its check should be valid.

What am I missing here?


Solution

  • The compiler is wrong and this should probably be considered an Eclipse compiler bug. Normally, the compiler will conclude you are dereferencing a variable earlier on, which makes sure that later in the code the variable is non-null. It probably got confused by this line:

    String cbNameF = (cbName == null || cbName.getF() == null) ? "null" : cbName.getF();
    

    It seems like you dereference cbName here, but you actually deference it only if it is not null. The variable may legally be null at the point where you check it and the else branch is not dead.

    If you are compiling with Eclipse, then cross-check with the reference compiler (javac).