I was working on a project, and I wrote some code which I expected to work fine. The snippet was like
But to my surprise, I got a Medium Priority Warnings
from findbugs
: RCN_REDUNDANT_NULLCHECK_WOULD_HAVE_BEEN_A_NPE: Nullcheck of value previously dereferenced
Basically it started complaining that I have non null check on a name on line 19
after it is being de-referenced at line 22
(the numbers are correct, bear with me for a while), so if the value was null, I would get NPE before even reaching this point.
This error in itself was super confusing, atleast for me. From what I understood here, we are creating Concrete, and checking if both the input are non null. Before it is initialized, we are passing this value super where we have non null check on name, and it is set as value.
So, I went and looked at the decompiled .class file. It was expanded as:
public Concrete(
@NonNull final String name,
@NonNull final String address
) {
super(name);
if (name == null) {
throw new NullPointerException("name");
}
this.address = address;
}
What was happening here was, the non null check was applied after calling the super class constructor, as opposed to before calling it, which is not what I would have expected. I thought that non null check will happen, before anything is executed in body, but I was definitely wrong.
Lombok is a super helpful tool, and it has made java much much (a couple of thousands much) less painful. But this incident reminded me again that no matter what, we should never just assume something while writing code.
This was a great learning for me.
Top comments (1)
It makes sense that lombok would put the check after the call to
super(name)
. Any call to a super constructor must be the first statement in the child constructor. It is a compile error otherwise. This is because the parent needs to be initialized before any parent methods may be called in the child constructor. I think that sincename
is already checked in the parent it shouldn't be checked in the child.