简体   繁体   中英

Get value of field with lombok builder

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM