I have a lot of classes with @NonNull
fields using Lombok builders.
@Builder
class SomeObject {
@NonNull String mandatoryField1;
@NonNull String mandatoryField2;
Integer optionalField;
...
}
However, this gives the caller the option to create the object without setting a mandatoryField
, which when used, would lead to a runtime failure.
SomeObject.builder()
.mandatoryField1("...")
// Not setting mandatoryField2
.build();
I'm looking for ways to catch these errors at build-time.
There are non-Lombok ways like StepBuilders or even a constructor to ensure mandatory fields are always set, but I'm interested in ways to achieve this using the Lombok builder.
Additionally, I understand that designing classes (like a step-builder, or an @AllArgsConstructor
) in order to have compile-time checks would create a lot of clumsy code - which is why I'm motivated to build a post-compile FindBugs step that detects these.
Now, FindBugs does fail when I explicitly set a @NonNull
field to null
:
FindBugs detects this failure,
new SomeObject().setMandatoryField1(null);
but it doesn't detect this:
SomeObject.builder()
.mandatoryField1(null)
.build();
Nor does it detect this:
SomeObject.builder()
.mandatoryField1("...")
//.mandatoryField2("...") Not setting it at all.
.build();
This seems to be happening because the Delomboked builder looks something like,
public static class SomeObjectBuilder {
private String mandatoryField1;
private String mandatoryField2;
private Integer optionalField;
SomeObjectBuilder() {}
public SomeObjectBuilder mandatoryField1(final String mandatoryField1) {
this.mandatoryField1 = mandatoryField1;
return this;
}
// ... other chained setters.
public SomeObject build() {
return new SomeObject(mandatoryField1, mandatoryField2, optionalField);
}
}
I observe that:
- Lombok doesn't add any
@NonNull
to its internal fields, nor does it add any null-checks to the non-null fields. - It doesn't call any
SomeObject.set*
methods, for FindBugs to catch these failures.
I have the following questions:
- Is there any way to use Lombok builders in a way that causes build-time failures (while running FindBugs, or otherwise), if
@NonNull
attributes are set? - Is there any custom FindBugs detector that detects these failures?