4

I am using the lombok @NonNull annotation for some of my fields, parameters and methods, partly for null checking, and also partly for documentation purpose. It is then confusing if I added a @NonNull/@NotNull annotation from other libraries.

Then if I also want to add a @Nullable/@CanNull annotation for some of my code, which one should I use? It doesn't exist in lombok (reasonably). If I declare my own annotation, IDEs may not understand them. If I use these annotations from existing libraries, other @NotNull annotations will also get added, and they may easily lead to using wrong annotations when I want the lombok one.

1

Since you can't alias annotations in Java, you must use both if you want to support both frameworks.

If a client chooses to use Lombok, it'll recognize it's annotation, ignoring the others. Without having Lombok's annotation, the framework will not register it, and same goes for any other framework.

Reducing the clutter

You chould avoid using @Nullable/@CanNull, make it implicit.

@NonNull/@NotNull is usually implemented to raise errors if someone attempts to use null where it's prohibited. If null is allowed, there's no circumstances where an error should be triggered (not including type safety reasons).

I'd understand if this is not an option (you must use null and non-null annotations), but it's a clever way reduce the verbosity.

  • 1
    "You should avoid using @Nullable/@CanNull, make it implicit." I don't really agree. Many developers just don't document most of their parameters for Java. Most parameters should not be null normally, but we usually only document the ones that the caller is tempted to pass null. @Nullable can explicitly specify that you will have special action if null is passed. – SOFe Nov 1 '16 at 15:27
  • @PEMapModder Think of it from a compile-time-safety point of view. @Nullable would be useful for triggering a warning suggesting the client to avoid null if wanted. But @NonNull could be used to trigger an error if a client uses null where it shouldn't be used, which is more beneficial. Making @NonNull implicit would allow the user to use null where it's not permitted, most likely causing a runtime problems. You don't need to make either implicit, you could use both from any framework you want to support, but if you were to choose one to lower verbosity, I'd recommend nullable – Vince Emigh Nov 2 '16 at 5:43

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.