Intellij Idea hint: Condition is always false - can that be true here? (Java)

Mathias Bader picture Mathias Bader · Aug 5, 2015 · Viewed 18.2k times · Source

I have the following code:

public String testExitPoints() {
    boolean myBoolean = false;
    try {
        if (getBoolean()) {
            return "exit 1";
        }
        if (getBoolean()) {
            throw new RuntimeException();
        }
    } finally {
        myBoolean = true;
    }
    if (getBoolean()) {
        return "exit 2";
    }
    return "exit 3";
}

public static boolean getBoolean() {
    Random rand = new Random();
    return rand.nextInt() > 100;
}

Now IntelliJ idea gives me for the second and third invocation of getBoolean() the following hint:

Condition 'getBoolean()' is always 'false'

Now to my understanding, that is not true, since getBoolean() can either be true or false, depending on the generated random value. Am I missing something here, or is that a bug in IntelliJ Idea?

Answer

Diego Martinoia picture Diego Martinoia · Aug 5, 2015

It's not a bug. It's a feature :)

If you look carefully in your IDE, it will tell you that the 2nd and 3rd call to getBoolean() are always false, but not the first one.

Idea assumes (in this case incorrectly) that your method, being parameterless and called "get"..., would return always the same value.

If that were the case, and the first call was true, the other would never be accessed (because of the return).

If the first call was false, so would be the others.

IDEA tries to be smart w.r.t. good coding practices, but it's not infallible.

If you change your method to have parameters (or rename it so it doesn't look like a getter)

public  boolean getBoolean(int x) {
    Random rand = new Random();
    return rand.nextInt() > 100;
}

The warnings will go away (even if you invoke with the same argument all times).

(Note that, even if it was a getter, if it's for a non-final field it's still wrong, as it may change in a multithreaded environment!)