Skip to content Skip to sidebar Skip to footer

Android @nonnull Usefulness

After a few reading and questions like this one I was wondering if there was a point in using @NonNull Android Support Annotation. I can see a very small warning from Android Studi

Solution 1:

Its main purpose is informational to your coworkers. One person is never the sole programmer of a large project. Using NotNull tells other programmers that the contract of the function means you can never send a null to it, so they don't do it. Otherwise I may make a logical assumption that calling setFoo(null) will clear Foo, whereas the API can't handle not having a Foo.

Solution 2:

Your #2 approach in my opinion is the correct way to do it for an API / Library. Use the annotation for static analysis to prevent compile-time attempts to call the method with null, and use a null check at runtime to give a useful exception (and to fail fast / protect from unexpected things from happening in your code) if a null object gets passed in. Use a //noinspection ConstantConditions directive before the null check to tell the IDE to suppress the warning (since you are checking null for a valid reason).

A random NPE indicates that the library/api author has possibly missed something and has a bug that isn't being handled in their code.

An IllegalArgumentException (or NPE with a description of the problem - which exception to use in this instance is an opinion-based argument) indicates that the caller has made a mistake in the way they called the method.

Ultimately though, whether to test for null after you've already annotated with @NonNull is going to be opinion-based and situation-dependent.

Solution 3:

It might be too late to comment, but better later than never :)

There is a Trautejavac plugin which inserts null-checks into generated bytecode based on method parameter's annotations.

Here is a sample Android project which illustrates that.

Post a Comment for "Android @nonnull Usefulness"