Android @NonNull usefulness

前端 未结 3 2162
生来不讨喜
生来不讨喜 2021-02-12 09:40

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 war

相关标签:
3条回答
  • 2021-02-12 10:23

    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.

    0 讨论(0)
  • 2021-02-12 10:27

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

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

    Here is a sample Android project which illustrates that.

    0 讨论(0)
  • 2021-02-12 10:31

    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.

    0 讨论(0)
提交回复
热议问题