3

I have some code which is similar to the following snippet:

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);
    }
}

And I got Findbugs reporting an 'NP_NULL_ON_SOME_PATH' issue.

Here is the description:

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.

My questions are:

  1. Can I treat it as a false positive in this example?
  2. Is it a good practice to put the null test in a separate method? The actual null check method is a bit longer than the sample method so I don't want to repeat the code everywhere.

Thanks!

imJude
  • 31
  • 1
  • 3
  • is it giving error for line 'doSomehing(o.getId())' ? – Peeyush May 21 '13 at 03:57
  • @Peeyush Yes, findbugs reports the issue for line 'doSomehing(o.getId())'. I have edited the sample code as in the real code the type of Object 'o' is some concrete class instead of just 'Object' so the error is not about the getId() method. – imJude May 21 '13 at 04:29

1 Answers1

0

It looks like FindBugs is not able to detect this case, at least with 2.0.2 in Eclipse. One workaround is to return the value from checkError and annotate the method with @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;
}
David Harkness
  • 35,992
  • 10
  • 112
  • 134
  • Is the `@Notnull` annotation necessary in your solution? The Java bean validation API is not used in my project at the moment. – imJude May 23 '13 at 06:22
  • @imJude - That's not the validation `@NotNull` annotation but rather `@Nonnull` from JSR-305. It tells FindBugs that `checkInput` will never return `null` and thus dereferencing the result is always safe. See http://stackoverflow.com/questions/4963300/which-notnull-java-annotation-should-i-use for some background. – David Harkness May 23 '13 at 17:44