PopKernel
PopKernel

Reputation: 4270

Do Java optional parameters make @NonNull annotations redundant?

I’m working on a new codebase and I’m wondering, since all non-optional parameters in my code throw an IllegalArgumentException when passed null, does it even make sense to use annotations like @NonNull? Or is it better to expect programmers know I always use Optional to indicate not passing in any value is a valid action here? (Of course assuming I also say that in javadoc, etc.)

Upvotes: 0

Views: 1097

Answers (2)

shmosel
shmosel

Reputation: 50776

Ultimately this is a matter of opinion and preference, but I don't think @NonNull is necessary if it's well established that your code is null-hostile. Guava takes such an approach and uses a @Nullable annotation to indicate the occasional exception.

Upvotes: 1

pedromss
pedromss

Reputation: 2453

You can pass a null to a parameter that expects an Optional so you could argue that @NonNull is still useful.

Personally I think @NonNull becomes redudant because if you call a method that expects an Optional you would pass Optional.empty() and never null when the value is absent. Keep in mind that java conventions discorages the use of Optional in parameters.

I disagree with this convention as Optional already conveys the meaning that the underlying method is prepared to deal with the absence of a value.

Upvotes: 1

Related Questions