3

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.

Josh M.
  • 26,437
  • 24
  • 119
  • 200
  • You should think about the meaning of word builder. Builder guesses what before command .build() your object is not consistent. – Dmitrii B Feb 18 '21 at 12:35
  • Do you have a constructive answer? I realize the intent of `builder`, but it seems reasonable to ask a builder "what value does this field have right now". If not, and there is no way, or it's an anti-pattern, that is fine -- that's all I'm asking. Thanks. – Josh M. Feb 18 '21 at 12:37
  • Yes, it's an antipattern. Before command .build() your object is not consistent you shouldn't see its intermediate state – Dmitrii B Feb 18 '21 at 12:39
  • 1
    That is a valid answer. If you'd like to add it as one, and elaborate, that'd be fine by me. – Josh M. Feb 18 '21 at 13:23
  • That's complete – Dmitrii B Feb 18 '21 at 15:36

0 Answers0