Android @NonNull usefulness

前端 未结 3 2163
生来不讨喜
生来不讨喜 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    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.

提交回复
热议问题