Domanda

Going through some old code written by one of my teammate, I found this really strange code:

if (...) {
    // some code

} else if (this == null) {
    System.out.println("I expected this to be dead code!");
}

Strange isn't it. AFAIK, this == null condition can never be true, which should be obvious to the compiler, as it knows the meaning of this and null both. But to my surprise, that wasn't marked as dead code.

I tried this code both in Eclipse, and through command line. I ran the following command to enable all warning:

javac -Xlint:all MyClass.java

Still it didn't gave any warning.

On contrary, if I change the else if block to:

else if (false) {
    System.out.println("As expected, this is dead code");
}

The statement inside was marked as dead code, as I expected.

So why this behaviour? This only leads me to think that there might be some condition where this can actually be null. Is it?

È stato utile?

Soluzione

The JLS has a definition of unreachable code:

The analysis takes into account the structure of statements. Except for the special treatment of while, do, and for statements whose condition expression has the constant value true, the values of expressions are not taken into account in the flow analysis.

So this is not considered "unreachable".

Also see this discussion about unreachable code errors and dead code warnings.

Altri suggerimenti

The compiler seems to be spotty in detecting implicitly-always-false conditions, and even if it is implied or stated by the JLS/is obviously false, then it may not pick up on that fact. The is-null check isn't as straightforward to catch when simply listing a set of "obvious conditions" to check, so it may have been overlooked.

Rice's theorem implies that checking whether a Java expression evaluates to false is undecidable. i.e. it is theoretically impossible to determine whether some arbitrary code is dead.

Since the java compiler cannot detect all dead code, the developers settled on a very specific set of instances of dead code that they could detect.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top