Intellij Idea提示:条件始终为假-在这里可以成立吗?(Java) [英] Intellij Idea hint: Condition is always false - can that be true here? (Java)

查看:183
本文介绍了Intellij Idea提示:条件始终为假-在这里可以成立吗?(Java)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码:

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;
}

现在IntelliJ想法为 getBoolean()的第二和第三次调用提供了以下提示:

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

Condition 'getBoolean()' is always 'false'

据我所知,那不是真的,因为 getBoolean()可以是 true false ,具体取决于生成的随机数价值.我在这里错过了什么吗,还是IntelliJ Idea中的错误?

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?

推荐答案

这不是错误.这是一个功能:)

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

如果您在IDE中仔细查看,它将告诉您对getBoolean()的第二次和第三次调用始终为false,而不是第一个.

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.

想法(在这种情况下是错误的)假设您的方法无参数并称为"get" ...,将始终返回相同的值.

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

如果是这种情况,并且第一个调用为true,则永远不会访问另一个调用(由于返回).

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努力变得聪明良好的编码习惯,但这并不是万无一失的.

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!)

这篇关于Intellij Idea提示:条件始终为假-在这里可以成立吗?(Java)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆