3

Java allows to mark arguments and returns as @Nonnull.

To me it feels like a bad practice, I don't want to tell in 99% of the use cases that it should be not null and pollute code with useless noise.

Instead I would prefer to tell it - everything in given package should be not null, unless I explicitly mark something as @CanBeNull.

Is it possible?

Alexey Petrushin
  • 1,311
  • 3
  • 10
  • 24
  • 1
    If you are using `Eclipse`, [the number of annotations can be reduced by declaring @NonNull as the default, using a @NonNullByDefault annotation at the package level.](http://help.eclipse.org/juno/index.jsp?topic=%2Forg.eclipse.jdt.doc.user%2Ftasks%2Ftask-using_null_annotations.htm) – Miserable Variable Feb 04 '16 at 01:03
  • IntelliJ: https://stackoverflow.com/questions/16938241/is-there-a-nonnullbydefault-annotation-in-idea – kol Nov 24 '22 at 17:35

1 Answers1

0

As far as I am aware the @Nonnull is there for tooling such as IDE's and to be honest I tend not to bother with it.

I would say its not strictly possible in Java, though there is nothing stopping you coming up with your own annotations, at which point it would only be useful to you and your team unless you updated the tooling (IDE's etc) to understand your annotation.

If you were to use a language like Swift or Kotlin by default val types can not be null, if you wish a val type to except null you add a ? to it to indicate it could possible be null in value.

Personally I use the JavaDoc to explain when I expect something to reject null on input, and when it will return null. Though with Java 8 if i expect a method to return null, I will use Optional to indicate a value may or may not be returned.

Gavin
  • 1,725
  • 21
  • 34