0

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.)

PopKernel
  • 4,110
  • 5
  • 29
  • 51

2 Answers2

1

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.

pedromss
  • 2,443
  • 18
  • 24
1

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.

shmosel
  • 49,289
  • 6
  • 73
  • 138