简体   繁体   中英

Should I mark both the interface and its implementation with the @NonNull annotation?

In the interface that describes the service, I have methods similar to this:

TaskCard saveTaskCard(@NonNull TaskCard card, User user);

I put the @NonNull (lombok) annotation before an argument, but it won't work on its own if the same annotation isn't in the implementation. This means that in the methods of the class implementing this interface, I will need to put this annotation again, thereby duplicating the code.

@Override
@Transactional
public TaskCard saveTaskCard(@NonNull TaskCard taskCard, User user) {
    taskCard.setUser(user);
    return repository.save(taskCard);
}

The question is, is this how it should be? If you put this annotation only in the interface, they will not work, and if you put it only in the class that implements the interface, then API users may not understand that null cannot be passed to these methods. What should I do?

IMHO you surely should duplicate it for the reasons you stated:

  • put it on the interface so that user see it
  • put it on the implementation so that Lombok can check it

It's only redundant, when you don't consider that nullability is actually part of the type - not in Java, but it reality (and eg, Kotlin), it is.

Unfortunately, Lombok can't do any better and it can access the interface (not parent class).

There are tools which may help you do this consistently (but I haven't tried them yet) or you can write a simple reflection-based test. Then, you'll still be forced to write redundant stuff, but you'll be reminded if you forget.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM