关于java:”更改此条件,使其不会总是评估为false”-SonarQube

“Change this condition so that it does not always evaluate to false” - SonarQube

我有下面的代码,我得到了SonarQube

Change this condition so that it does not always evaluate to false

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
@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的人来说,我的代码还可以吗?那我该怎么做?


对于hashCodeVariable的null测试是没有意义的,因为在第一种情况下,对它使用了.equals。

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

hashCodeVariable为!null,否则在第一个if语句中将引发NullPointerException。因此条件为假。


那时候hashCodeVariable不为空,因为否则会在前一个if块中抛出NullPointerException。该条件为false&&短路了,所以false && whateverfalse,没有进行任何评估。