【问题标题】:"Change this condition so that it does not always evaluate to false" - SonarQube“更改此条件,使其不会总是评估为假” - SonarQube
【发布时间】:2018-08-01 00:14:23
【问题描述】:

我有以下代码,我得到一个 SonarQube

更改此条件,使其不会总是评估为假

这行代码 if(hashCodeVariable == null && equalsVariable.equals(EQUALS_METHOD)) { 是给我 sonarqube 错误的代码。

@Override
  public void visitNode(Tree tree) {
    MethodTree mt = null;
    ClassTree classTree = (ClassTree) tree;
    if (!hasSemantic()) {
      return;
    }
    for (Tree memberTree : classTree.members()) {
      if (memberTree.kind().name().equals(Kind.METHOD.name())) {
        mt = (MethodTree) memberTree;
        methods.add(mt);
      }
    }
    storeMethodValue(mt);
  }

  public void storeMethodValue(MethodTree mt) {
    String methodName;
    try {
      for (MethodTree method : methods) {
        methodName = PUBLIC + SPACE + method.returnType().symbolType().name()
            + SPACE + method.symbol().name();
        checkMethodName(methodName);
      }
      if(hashCodeVariable.equals(HASH_CODE_METHOD) && equalsVariable == null) {
        reportIssue(mt, "in");
        return;
      }

      if(hashCodeVariable == null && equalsVariable.equals(EQUALS_METHOD)) {
        reportIssue(mt, "out");
        return;
      }
    }
    catch (NullPointerException nullPointer) {
      throw nullPointer;
    }
  }

  public void checkMethodName(String methodName) {
    if (methodName.equals(EQUALS_METHOD)) {
      equalsVariable = methodName;
    } else if (methodName.equals(HASH_CODE_METHOD)) {
      hashCodeVariable = methodName;
    }
  }

对于那些熟悉使用Tree 的人来说,我的代码还可以吗?我应该做些什么改变?

【问题讨论】:

    标签: java tree sonarqube


    【解决方案1】:

    此时hashCodeVariable 是非空的,因为否则NullPointerException 将在前一个if 块中抛出。那个条件是false&& 是短路的,所以 false && whateverfalse,没有进行任何评估。

    【讨论】:

      【解决方案2】:

      对 hashCodeVariable 的 null 测试毫无意义,因为在第一种情况下使用了 .equals。

       if(hashCodeVariable.equals(HASH_CODE_METHOD) && equalsVariable == null) {
       ...
       if(hashCodeVariable == null && equalsVariable.equals(EQUALS_METHOD)) {
      

      hashCodeVariable 为 !null,否则在第一个 if 语句中会引发 NullPointerException。所以条件为假。

      【讨论】:

        猜你喜欢
        • 2018-05-07
        • 2017-02-02
        • 2018-10-04
        • 2021-01-05
        • 2018-02-10
        • 2017-06-12
        • 2016-05-14
        • 2020-01-11
        • 2016-11-25
        相关资源
        最近更新 更多