3

我有一些类似于以下代码段的代码:

public void foo(Order o) {
    ...
    checkInput(o, "some error message");
    doSomehing(o.getId());
}

private void checkInput(Object o, String message) {
    if (o == null) {
        throw new SomeRuntimeException(message);
    }
}

我让 Findbugs 报告了“NP_NULL_ON_SOME_PATH”问题。

这是描述:

There is a branch of statement that, if executed, guarantees that a null value will be dereferenced, which would generate a NullPointerException when the code is executed. Of course, the problem might be that the branch or statement is infeasible and that the null pointer exception can't ever be executed; deciding that is beyond the ability of FindBugs.

我的问题是:

  1. 在此示例中,我可以将其视为误报吗?
  2. 将空测试放在单独的方法中是一种好习惯吗?实际的空值检查方法比示例方法长一点,所以我不想到处重复代码。

谢谢!

4

1 回答 1

0

看起来 FindBugs 无法检测到这种情况,至少 Eclipse 中的 2.0.2 是这样。一种解决方法是从方法返回值checkError并使用@Nonnull.

public void foo(Order o) {
    ...
    doSomehing(checkInput(o, "some error message").getId());
}

@Nonnull
private Order checkInput(Order o, String message) {
    if (o == null) {
        throw new SomeRuntimeException(message);
    }
    ...
    return o;
}
于 2013-05-21T22:34:24.403 回答