Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does findbugs give redundant nullcheck for one method but not the other

Tags:

java

findbugs

I've been using the @Nonnull and @Nullable annotations on methods to give other programmers (and myself!) a clue about what a method can return. I finally decided to actually run Findbugs on a class (IntelliJ - FindBugs-IDEA v1.0.1), and I don't understand the behavior I'm seeing. The documentation hasn't helped either.

Let's say I have the following example code:

import javax.annotation.Nonnull;

public class Main {

    public static void main(String[] args) {
    }

    @Nonnull
    public static String myFunc(){
        return new String("foo");
    }

    @Nonnull
    public static String myFunc2(){
        return "foo";
    }
}

Findbugs flags myFunc()'s return statement as having "Redundant nullcheck of value known to be non-null", but is happy with myFunc2().

Is it expected that findbugs sees these differently? (Link to documentation would be appreciated) Am I completely misunderstanding the use of @Nonnull on methods?

[edit]

After some research, I've decided that the org.jetbrains @Contract annotation (with contract violations changed to errors) will better serve my needs. Thank you Guillaume F. for your help!

like image 857
KathyA. Avatar asked Jan 26 '17 22:01

KathyA.


1 Answers

You have to understand what redundant Null-Check means. When Findbugs gives you this warning, it means you did a Null-Check two times, and the second time is not necessary. Which matches your example.

In the first code, new String("foo") does an implicit null check, because new String(null) will throw an Exception. So this new String object is checked non-null implicitly. Then you do another @Nonnull check while leaving the method. Findbugs sees this and gives you the warning.

In your second code, there is no such control since you return a raw String and do the @Nonnull check only once. Everything is fine.


Maybe you will want to use edu.umd.cs.findbugs.annotations.NonNull instead. This one will just hint Findbugs that you want a non-null result, without having a real check.

If you are using Maven:

    <dependency>
        <groupId>com.google.code.findbugs</groupId>
        <artifactId>annotations</artifactId>
        <version>${findbugs-annotations.version}</version>
        <scope>provided</scope>
    </dependency>

https://blogs.oracle.com/java-platform-group/entry/java_8_s_new_type

Which @NotNull Java annotation should I use?

like image 92
Guillaume F. Avatar answered Nov 11 '22 02:11

Guillaume F.