Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where to put @Nullable on methods with nullable return types? [duplicate]

When using javax.annotation.Nullable to mark methods as "potentially returning null value", where to put the @Nullable annotation? On the method, or return type?

Is there any technical difference, or is this strictly a style issue?

Style A:

@Nullable
public Object blah() { ... }

Style B:

public @Nullable Object blah() { ... }
like image 225
kevinarpe Avatar asked Sep 21 '14 12:09

kevinarpe


1 Answers

This is strictly a style issue.

No matter where you write the annotation in the source code, the annotation is actually on the method. That's because of the @Target meta-annotation on the definition of javax.annotation.Nullable, which makes javax.annotation.Nullable a method annotation. You are allowed to write the annotation in either location, because the Java Language Specification grammar permits method annotations to be interspersed with method modifiers such as public.

I consider it clearer to place the annotation before the return type. After all, it's the return type that is non-null. It doesn't make sense to say that a method itself is non-null.

Placing the annotation before the return type has another important benefit: your code is compatible with versions of Nullable that are defined as type annotations. Type annotations were introduced in Java 8. They are more expressive than method annotations, and they enable more powerful checking. For example, the Nullable annotations supported by Eclipse and the Checker Framework are type annotations.

like image 187
mernst Avatar answered Sep 23 '22 13:09

mernst