java - fb-contrib :SEO_SUBOPTIMAL_EXPRESSION_ORDER? 的误报

标签 java findbugs sonarqube5.6

SonarQube 认为以下代码违反了规则 fb-contrib:SEO_SUBOPTIMAL_EXPRESSION_ORDER(请注意,代码示例已简化且不符合逻辑):

class Foo {

   boolean baz;

   boolean foo() { 
      return bar() && baz==Baz.VALUE; //Violation of fb-contrib:SEO_SUBOPTIMAL_EXPRESSION_ORDER
   }

   boolean bar() { 
      return baz == Baz.VALUE_2; 
   }

}

enum Baz {
    VALUE, VALUE2
}

Performance - Method orders expressions in a conditional in a sub optimal way (fb-contrib:SEO_SUBOPTIMAL_EXPRESSION_ORDER)

This method builds a conditional expression, for example, in an if or while statement where the expressions contain both simple local variable comparisons, as well as comparisons on method calls. The expression orders these so that the method calls come before the simple local variable comparisons. This causes method calls to be executed in conditions when they do not need to be, and thus potentially causes a lot of code to be executed for nothing. By ordering the expressions so that the simple conditions containing local variable conditions are first, you eliminate this waste. This assumes that the method calls do not have side effects. If the method do have side effects, it is probably a better idea to pull these calls out of the condition and execute them first, assigning a value to a local variable. In this way you give a hint that the call may have side effects.

我认为规则实现查看实际表达式内部是合理的,如果内容是值检查则不会触发违规。

这是错误还是我遗漏了什么?

最佳答案

您几乎已经在问题中给出了答案:

This causes method calls to be executed in conditions when they do not need to be, and thus potentially causes a lot of code to be executed for nothing. By ordering the expressions so that the simple conditions containing local variable conditions are first, you eliminate this waste.

FB-Contrib 希望您改变表达方式:

boolean foo() { 
    return baz==Baz.VALUE && bar();
}

这样,只有在baz==Baz.value时才需要执行bar()。当然,这是编译器或 JVM 可能会优化的内容,因此可以归结为一个微基准来确定是否确实需要这种预防措施。

但这在语法层面上是有意义的,因为调用方法通常比值检查更昂贵。所以你不需要查看方法内部来告诉它。无论如何,对编译器/JVM 的内联行为的任何猜测都可能是错误的。

关于java - fb-contrib :SEO_SUBOPTIMAL_EXPRESSION_ORDER? 的误报,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42693012/

相关文章:

java - Jackson无法解析json,返回NPE

java while (scan.nextLine() != "$")

Java 递归方法是如何工作的?

java - 当 null 测试在单独的方法中时,出现 Findbugs 问题 “NP_NULL_ON_SOME_PATH”。这是误报吗?

java - SonarQube 5.6.2 插件 - 自定义扩展点未执行

java - java中字段初始化的过程

java - Checkstyle 与 PMD

java - Swing 未写字段警告(Java)

java - 在 sonar.properties 中禁用 SCM 不起作用