How I misunderstood Lombok

Posted on

I was working on a project, and I wrote some code which I expected to work fine. The snippet was like


import lombok.NonNull;
import com.google.inject.Inject;
public abstract class Base {
@NonNull protected final String name;
protected Base(@NonNull final String name) {
this.name = name;
}
public abstract String getInfo();
}
public class Concrete extends Base {
@NonNull private final String address;
@Inject
public Concrete(
@NonNull final String name,
@NonNull final String address
) {
super(name);
this.address = address;
}
@Override
public String getInfo() {
return this.name + lives in + this.address;
}
}

view raw

initial.java

hosted with ❤ by GitHub

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;
}
Enter fullscreen mode

Exit fullscreen mode

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.

Leave a Reply

Your email address will not be published. Required fields are marked *