IntelliJ IDEA 警告 "value is never used"

IntelliJ IDEA warning "value is never used"

我写了一个计算单词最大排列数的方法,但是 IntelliJ IDEA 给我警告:

The value length - 1 assigned to 'permutationAmount' is never used

private static int permutationsPossible(String word) {
    //Amount of letters in word.
    int length = word.length();

    //Return length if length is less than or equal to 1.
    if (length <= 1)
        return length;

    //Calculate maximum amount of permutations.
    int permutationAmount = length;
    for (int i = 1; i < length - 1; i++)
        permutationAmount *= (length - i);
    return permutationAmount /= length - 1;
}

但是,当我像这样创建一个 helper int 时,没有显示警告:

    permutationAmount = permutationAmount /= length - 1;
    return permutationAmount;

该程序在两种情况下都运行良好,我想知道的是,为什么 IntelliJ 警告我从未使用过 'length - 1'?

截图:https://i.gyazo.com/886d7ab8b06398fb7dd0809a7d1bbaf3.png

您在 return 语句中无缘无故地向 permutationAmount 赋值(警告的原因)。

return permutationAmount / (length - 1);

棘手的部分可能是,虽然它 看起来 就像您在 return 语句 return 中计算 permutationAmount 的值一样(因此会读取分配的值),你不是。 return 语句实际上是 return 赋值操作的结果,因此 permutationAmount 在赋值后实际上不会再次读取。

这是因为您无缘无故地更改了 permutationAmount 的值。在 return 之后您没有再次使用新值,因此您实际上没有必要更改 return 行中变量的值。您可以通过执行

来完成相同的事情,而不是实际更改值
return permutationAmount / length - 1;

在您的第二个示例中,您使用的是更改后的新值,如果您实际上并未更改该值,则 return 将不正确。

这是当我在 IntelliJ 中针对此警告展开框时出现的文本:

This inspection points out the cases where a variable value is never used after its assignment, i.e.:

  • the variable never gets read after assignment OR

  • the value is always overwritten with another assignment before the next variable read OR

  • the variable initializer is redundant (for one of the above tow reasons) OR

  • the variable is never used.

似乎是由于第一个原因触发了此警告:您在分配变量后再也没有读取它。这没有多大意义,因为您立即 return 变量。

但是,给局部变量赋值然后立即return它没有多大意义。这一行将执行相同的逻辑,而不分配给变量:

return permutationAmount / (length - 1);

所以并不是说这个变量从来没有被使用过,因为我们假设这个方法的调用者会读取到这个方法return的值,但是给变量赋值是没有用的