Java: @Nonnull used with boxed primitive type


(Simon Kissane) #1

Consider a Java field declaration like this:

@Nonnull private Integer id;

That is inefficient, since there is no need for a boxed primitive type here if we are also saying the field cannot be null. The boxing will just slow things down, consume more memory, increase load on garbage collector, etc.

So, my suggestion is, a rule that flags use of @Nonnull (and equivalent annotations such as @NotNull and @NonNull) on a field/parameter/return type with a boxed primitive (Boolean, Byte, Short, Character, Integer, Long, Float, Double). In most of those cases, one wants to use the unboxed primitive type instead.

(There are some exceptions; e.g., sometimes implementing a generic interface, or extending from a generic superclass, forces you to use a boxed instead of unboxed type, and in that case annotating it as @Nonnull can still be useful – to avoid false positives in those cases, it might make sense to exclude the rule from applying to inherited/overridden methods.)

(Adam Gabryś) #2

There is a rule RSPEC-4682 “@CheckForNull” or “@Nullable” should not be used on primitive types. It would be nice to just extend it :slight_smile: