Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When to use @NotNull and @Nullable IntelliJ annotations?

I just started working with those IntelliJ IDEA Java annotations, but I do not understand when I should use them, especially because IDEA is able to infer them most of the time.

Do you guys follow some sort of rule? I wouldn't like to see every parameter or field annotated with them, code would become a mess probably.

I understand this could be considered opinion-based, but still, I'd like to read answers.

like image 754
LppEdd Avatar asked Oct 03 '18 15:10

LppEdd


1 Answers

The @Nullable and @NotNull annotations are used to indicate the IDE that something (argument, attribute, etc) can (or cannot) be null. This way it helps you to detect possibly incorrect code.

This is not a "must follow" rule, but another tool to help the developer in coding a more robust and less error-prone code while using the IDE.

If you're coding alone, the team is small, you're working in a small project or any similar situation... and you feel comfortable without it, then don't use it as it is true the code becomes somehow verbose. This doesn't mean this is not useful for any of the previous situations (it can actually be very helpful too).

On the other hand, if you think you need an extra tool to help you detect possibly failing code against not "nullable" values, or, for instance, you're coding an API to be used by a third party and want to use this annotation instead of several asserts inside the code block... then go for it.

It is all about evaluating pros and cons in the project where you might apply these annotations and decide whether this could give you more benefits than the "problems" it can cause.

like image 195
lealceldeiro Avatar answered Oct 07 '22 17:10

lealceldeiro