FindBugs & Reject.if* False Positives

In my current project we’re using Reject.if* (ifNull, ifNotNull, ifTrue…) methods for several validations, error management etc. As we’re also using FindBugs, we stumbled upon a problem with code like the following, in which FindBugs comes up with a NP_NULL_ON_SOME_PATH warning, in this case a false positive:

void foo(String bar) {
    Reject.ifNull(bar);
    bar.getBytes();
}

After searching for a solution and asking some people, we finally found a solution that works pretty well in this case: Passing a system property called findbugs.assertionmethods [1] through Maven to FindBugs. The code for it in the pom looks somewhat like this:

...
<plugin>
    <groupId>org.codehaus.mojo</groupId>
    <artifactId>findbugs-maven-plugin</artifactId>
    <version>2.5</version>
    <configuration>
        <effort>Default</effort>
        <threshold>Medium</threshold>
        <xmlOutput>true</xmlOutput>
        <findbugsXmlOutputWithMessages>true</findbugsXmlOutputWithMessages>
        <omitVisitors>FindReturnRef</omitVisitors>
        <jvmArgs>-Dfindbugs.assertionmethods=de.mopri.utils.Reject.ifNull</jvmArgs>
    </configuration>
</plugin>
...

By using the jvmArgs element the system property is properly passed down to FindBugs and telling it that the method Reject.ifNull is used as an assertion. Now FindBugs acknowledges that bar.getBytes() won’t throw a NullPointerException :)

Control flow with exceptions :D

Reminds me about some discussions I had about controlling your program flow with exceptions :mrgreen:

Using exceptions to control program flow is a bad idea. Creating exceptions requires taking a snapshot of the call stack, and that’s costly. – John Flinchbaugh Oct 16 ’08 at 12:17

Not if you override the method that generates the call stack in the exception you throw to do nothing. That’s the advantage of a custom exception. – shemnon Oct 17 ’08 at 14:03

The whole thread can be found here on stackoverflow.