如何在 for 循环中解决 SonarQube 抱怨者?

Jin*_*won 3 java for-loop sonarqube

我写了一个方法将字节从 an 复制InputStream到 an OutputStream

// copies bytes from given input stream to specified output stream
// returns the number of bytes copied.
private static long copy(final InputStream input,
                         final OutputStream output)
        throws IOException {
    long count = 0L;
    final byte[] buffer = new byte[4096];
    for (int length; (length = input.read(buffer)) != -1; count += length) {
        output.write(buffer, 0, length);
    }
    return count;
}
Run Code Online (Sandbox Code Playgroud)

SonarQube 抱怨。

此循环的停止条件测试“长度、输入、缓冲区”,但增量器更新“计数”。

当 for 循环的停止条件和增量器不作用于同一个变量时,它几乎总是一个错误。即使不是,它也可能混淆代码的未来维护者,应该避免。

有没有更好的代码用于相同的目的?

更新

正如答案所推荐的那样,我确实喜欢这个并且问题消失了。

// copies bytes from given input stream to specified output stream
// returns the number of bytes copied.
private static long copy(final InputStream input,
                         final OutputStream output)
        throws IOException {
    long count = 0L;
    final byte[] buffer = new byte[4096];
    for (int length; (length = input.read(buffer)) != -1;) {
        output.write(buffer, 0, length);
        count += length;
    }
    return count;
}
Run Code Online (Sandbox Code Playgroud)

Tun*_*aki 5

您正在滥用for循环,这就是 SonarQube 发出警告的原因。在以下循环中,您count在更新子句中递增,但停止条件不依赖于count

for (int length; (length = input.read(buffer)) != -1; count += length) {
                 ^---------------------------------^  ^-------------^
                      does not depend on count        increments count
Run Code Online (Sandbox Code Playgroud)

相反,您应该使用while循环并增加循环体​​内的计数:

private static long copy(final InputStream input, final OutputStream output) throws IOException {
    long count = 0;
    final byte[] buffer = new byte[4096];
    int length;
    while ((length = input.read(buffer)) != -1) {
        output.write(buffer, 0, length);
        count += length;
    }
    return count;
}
Run Code Online (Sandbox Code Playgroud)