已知为 null 的值的冗余 nullcheck

Redundant nullcheck of value known to be null

我有一段代码看起来像这样:

private void methodA(String a String b){
  Employee e1=null;
  foobar(e1,b); //line 1
  //do something
  if(e1!=null){ //line 2
    //flow1
  }else{
    //flow2
  }
}
private void foobar(Employee e, String a){
  e= new Employee();
  //do stuff
}

当我 运行 为这个 class 找到错误时,它在第 1 行显示了两个警告 -

Load of known null value
The variable referenced at this point is known to be null due to an earlier check against null. Although this is valid, it might be a mistake (perhaps you intended to refer to a different variable, or perhaps the earlier check to see if the variable is null should have been a check to see if it was nonnull).

在第 2 行:

Redundant nullcheck of value known to be null
This method contains a redundant check of a known null value against the constant null.

为了避免这些警告,我改为执行以下操作:

private void methodA(String a String b){
  Employee e1 = foobar(b); //line 1
  //do something
  if(e1!=null){ //line 2
    //flow1
  }else{
    //flow2
  }
}
private Employee foobar(String a){
 if("some_value".equals(a)){
  Employee e= new Employee();
  //do stuff
  return e;
  }
return null;
}

这样做会删除 findbugs 的警告,但我的问题是这种更改是绝对必要的,或者更确切地说,第一种方法会产生什么影响?

Employee e1=null;
foobar(e1,b);

这是不正确的,因为 foobar() 得到 null 并且 e1 不能引用到它后面的对象。所以 if(e1!=null) 总是 false.


Employee e1=null;
...
private void foobar(Employee e, String a){
  e= new Employee();
  //do stuff
}

e 引用新对象,但这是方法的 局部变量