record-builder icon indicating copy to clipboard operation
record-builder copied to clipboard

Builder defaults for collections are inconsistent with output record

Open fprochazka opened this issue 3 years ago • 3 comments

Hi, awesome library! Love it! I just have a small suggestion...

If I have a record with any collection

@MyRecordBuilder // with useImmutableCollections = true, interpretNotNulls = true
public record Costs(
    @Nullable BigDecimal shipping,
    Map<String, Object> extraData
) { }
  • the default values when the builder initializes for all fields is null
  • calling CostsBuilder.builder().build().extraData() builds instance of Costs that has extraData initialized with empty Map.of() and does not return null
    • which means CostsBuilder.builder().build().extraData().get("value") will not throw NPE
  • calling CostsBuilder.builder().extraData() returns the default null
    • which means CostsBuilder.builder().extraData().get("value") will throw NPE

I'm proposing that since you're adding special handling of collections and always initializing them, they should also be initialized to empty collections when the empty builder is created, so that the second case will also not throw an NPE

fprochazka avatar Jul 19 '22 12:07 fprochazka

Could these be combined into a single PR? Maybe with a new option to avoid breaking existing code.

Randgalt avatar Jul 21 '22 06:07 Randgalt

@Randgalt I've created two issues because I expected others to have a different opinion and you might be willing to accept only one part of the proposal, but both of the issues are related in my mind.

fprochazka avatar Jul 21 '22 10:07 fprochazka

Isn't this one solved by this?

hofiisek avatar Oct 26 '23 12:10 hofiisek