When to use @NotNull and @Nullable IntelliJ annotations?
@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.
It's probably most useful to use these annotations on public API's, where they can't be inferred automatically by IntelliJ IDEA. In other words to communicate with other developers. So the parameters and return types of public methods in public interfaces are definitely candidates for
@Nullableannotation helps you detect:
Method calls that can return null. Variables (fields, local variables, and parameters), that can be
@NotNullannotation is, actually, an explicit contract declaring that:
A method should not return
nullVariables (fields, local variables, and parameters) cannot hold a
For example, if you create a method where a parameter has the
@NotNull annotation, and then call this method with a parameter that potentially can be
null, IntelliJ IDEA will highlight the problem on the fly.
@Nullable just to declare that your variable or method can hold a