Get value of field with lombok builder

Viewed 1136

Is it possible to retrieve the value of a field on a builder which was generated by lombok?

final var builder = Something.builder();

try {
    // ... something that might break
}
catch (Throwable t) {
    builder.error("Something went wrong.");
    builder.success(false);
}

// don't continue if the builder is already marked as not-successful
if (builder.isSuccess() != null && builder.isSuccess()) {
 // ... do some more work / set more fields on the builder
}

return builder.build();

It seems that lombok builders do not expose getters for the fields they can build, so in the code above, builder.isSuccess() doesn't exist. Is it possible to do this, or is it an anti-pattern?

The alternative is to return from the catch block, but IMO multiple returns in a method lead to harder to follow code, so I would like to avoid that and just return the builder at the end of the method.

1 Answers

It's an antipattern. Before command .build() your object is not consistent you shouldn't see its intermediate state, because the builder shouldn't have any getters. Before getting the field's value complete its creating.

Related