@NotNull vs. @Nullable

Hello, Everybody,

Recently I encountered an issue with our annotations, that I feel we are
doing the wrong way now.
Specifically I had a method annotated with @Nullable in a base class, and
consequently when looking into subclass' code,
I was presented with a bunch of warnings on dereferencing the object got
from calling that method. However in the subclass
I know that @NotNull is actually the case. I could certainly override the
method with covariant @NotNull annotation, but
I feel this is a wrong way to go, since overriding is a runtime feature,
that should not be used for enforcing static contracts.
Have you ever had such problems, and after all is it really a problem, or
just my imagination?

Eugene.


2 comments

Eugene Vigdorchik (JetBrains) wrote:

Recently I encountered an issue with our annotations, that I feel we are
doing the wrong way now.
Specifically I had a method annotated with @Nullable in a base class, and
consequently when looking into subclass' code,
I was presented with a bunch of warnings on dereferencing the object got
from calling that method. However in the subclass
I know that @NotNull is actually the case. I could certainly override the
method with covariant @NotNull annotation, but
I feel this is a wrong way to go, since overriding is a runtime feature,
that should not be used for enforcing static contracts.
Have you ever had such problems, and after all is it really a problem, or
just my imagination?


I don't see any conceptual problem with overriding @Nullable with
@NotNull. It's quite conceivable that a subclass can override a
baseclass' method and enforce @NotNull.

And I don't see how overriding is a runtime feature?

Ciao,
Gordon

--
Gordon Tyler (Software Developer)
Quest Software <http://www.quest.com/>
260 King Street East, Toronto, Ontario M5A 4L5, Canada
Voice: (416) 933-5046 | Fax: (416) 933-5001

0

Eugene Vigdorchik (JetBrains) wrote:

I know that @NotNull is actually the case. I could certainly override the
method with covariant @NotNull annotation, but
I feel this is a wrong way to go, since overriding is a runtime feature,
that should not be used for enforcing static contracts.


Hmm, it seems indeed strange to override a method just to annotate it with @NotNull, but
I don't really consider this a runtime feature in the sense of polymorphism.

class Base { @Nullable Object foo() { ... } }
class Test extends Base {
@NotNull Object foo() {
Object o = super.foo();
assert o != null;
return o;
}
}

Through overriding the method and adding the assert there's also a documentation aspect
for the overridden method's semantics. I personally don't consider this to be a problem,
but I have to admit that I haven't been in the exactly same situation yet ;)

Sascha

0

Please sign in to leave a comment.