java - 如何解决 for-loop 中的 SonarQube 提示者?

标签 java for-loop sonarqube

我编写了一个方法,将字节从 InputStream 复制到 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;
}

SonarQube 提示。

This loop's stop condition tests "length, input, buffer" but the incrementer updates "count".

It is almost always an error when a for loop's stop condition and incrementer don't act on the same variable. Even when it is not, it could confuse future maintainers of the code, and should be avoided.

对于相同的目的,是否有更好的代码?

更新

按照建议的答案,我确实喜欢这个,问题消失了。

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

最佳答案

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

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

相反,您应该使用 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;
}

关于java - 如何解决 for-loop 中的 SonarQube 提示者?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35719682/

相关文章:

java - 在脚本标记中使用&符号时 Thymeleaf 呈现错误

c++ - 是否可以避免 for 循环来计算矩阵条目?

java - GC 和在 for 循环中赋值

go - 如何使用Jenkins运行SonarQube for Go代码

postgresql - sonar启动时无法连接postgreSQL

java - Reactive Java Subscription 是一个什么样的对象?

java - 缓存类似集合的集合

javascript - 在 javascript 中使用 java 变量 - webDriver

javascript - combineReducer 中使用的 reducer 的 Sonar 代码气味

java - 在循环和方法内使用 return