top | item 22482579

(no title)

leibnitz27 | 6 years ago

negative instanceof is a disaster

I posted a bit about it here http://www.benf.org/other/cfr/java14instanceof_pattern.html

it was first noted https://twitter.com/tagir_valeev/status/1210431331332689920 here

but the main thing is that if the 'taken' conditional is guaranteed to exit, then scope hiding happens, if not, not.

But in java

if (true) { throw new Exception(); }

is not guaranteed to exit.

So: https://github.com/leibnitz27/cfr_tests/blob/master/src_14/o...

In case you don't want to run, as of java (build 14-ea+34-1452) this prints:

Fred

WIBBLE

  public class InstanceOfPatternTest10 {
    static String s = "WIBBLE";

    public static void test(Object obj) {
        if (!(obj instanceof String s)) {
            throw new IllegalStateException();
        }
        System.out.println(s);
    }

    public static void test2(Object obj) {
        if (!(obj instanceof String s)) {
            if(true) {
                throw new IllegalStateException();
            }
        }
        System.out.println(s);
    }

    public static void main(String ... args) {
        test("Fred");
        test2("Fred");
    }
}

discuss

order

vbezhenar|6 years ago

Looks like a bug. But anyway should be easily detectable by a static analysis and reported as a warning, so not a big deal in practice, even if working as intended.

leibnitz27|6 years ago

Nope - the if condition is not considered in flow analysis. Read the end:

https://docs.oracle.com/javase/specs/jls/se8/html/jls-14.htm...

"14.21. Unreachable Statements It is a compile-time error if a statement cannot be executed because it is unreachable.

This section is devoted to a precise explanation of the word "reachable." The idea is that there must be some possible execution path from the beginning of the constructor, method, instance initializer, or static initializer that contains the statement to the statement itself. 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."

Jenz|6 years ago

Ooops