NeonOverflow
NeonOverflow

Reputation: 31

When is it appropriate to annotate something as @NotNull in Java?

This is my first question on here and I'm pretty new to Java, so please pardon me if this is kind of a silly question.

I am working on "documenting" the expected behavior of my application from within using JavaDocs and annotations, but I'm just curious if it's appropriate or good practice to use @NotNull on a method that SHOULDN'T ever return null, but may due to future developer error.

Thanks.

Upvotes: 3

Views: 1825

Answers (3)

Harish Dalmia
Harish Dalmia

Reputation: 138

yes it is good practice to use @NotNull. The @NotNull Annotation is, actually, an explicit contract declaring the following:

  1. A method should not return null.
  2. A variable (like fields, local variables, and parameters)cannot hold a null value.

So to keep it simple, it is a good practice.

Upvotes: 0

mnestorov
mnestorov

Reputation: 4494

As far as I'm aware, there is not enforced standard globally to use these types of annotations. It makes sense to use them when writing a public API, but this is project specific.

In any case, feel free to do so in your project if it would help with code clarity and readability.

It's not an anti-pattern to have javadocs with annotations.


Also, if you are considering of warning the user of your method that it shouldn't return a null, but there is a chance of that happening (since you cannot enforce it), you might want to look into the Optional class.

Upvotes: 2

Sam
Sam

Reputation: 9987

This really depends on what tooling you're using. The @NotNull annotation doesn't actually do anything. Actually, there are several different @NotNull annotations provided by different libraries. None of them do anything on their own, other than signalling the programmer's intent.

To make the annotation do anything, you need to combine it with a tool that will process the annotation (either at compile time or at run time) and apply some validation to your code or your data. For example:

  • IntelliJ IDEA contains tools which will check that your code abides by the nullability annotations you've included.
  • Bean validation can be used at runtime to check, for example, that user input doesn't violate the nullability constraints.

Even without the tooling, I would say that yes, these annotations can be useful to signal intent. You can always remove the annotation if it becomes untrue.

It sounds like it would be a good idea in your case for all contributors to the codebase to use a tool, like IntelliJ IDEA, that will check for compliance with these annotations at compile time. That will help you to avoid the type of developer error that you describe.

Upvotes: 3

Related Questions