Randgalt / record-builder

Record builder generator for Java records
Apache License 2.0
756 stars 55 forks source link

Empty collections by default using RecordInterface #152

Open JanecekPetr opened 1 year ago

JanecekPetr commented 1 year ago

My goal: Never to get a null from any Collection-like component.

Currently there's the useImmutableCollections option for this, however that's not perfect. First of all, it does not work with SortedSet / NavigableSet / SortedMap / NavigableMap, but also e.g. Guava's collections types (https://github.com/Randgalt/record-builder/issues/151). Also the record's canonical constructor can still be used directly, circumventing record-builder, and that makes any guarantees shaky. One more problem: collection copying has a cost, and our team actually decided to not use useImmutableCollections by default, so in our case it would not help even it all the previous reasons were void.

One can use the Validation API, but again that can be circumvented.

Therefore, the only way to make this work all the time is to manually write checks:

record Car(List<String> passengers) {

    Car {
        if (passengers == null) {
            passengers = List.of();
        }
    }

}

This of course works, but it's a relatively big piece of manual code that has to be in every record.

Would be nice if record-builder did this out-of-the box for @RecordInterface-generated records. No more nulls, ever!

Randgalt commented 1 year ago

I was working on something similar with this: https://github.com/Randgalt/record-builder/discussions/120 - but that was way more experimental.

pawellabaj commented 1 year ago

@JanecekPetr I work on a library we using in our projects to generate records based on an interface: auto-record.

It generates boiler plate code for a nullability checking in a compact constructor (we use nonNull by deafult approach), see examples at https://github.com/pawellabaj/auto-record/wiki/Nullability

I think generating empty collections in a compact constructor could be added as an option.

Anupam2528 commented 1 year ago

Hey @JanecekPetr / @Randgalt are we trying to implement emptyInNull kind of scenario here? could you please let me know?

Randgalt commented 1 year ago

I'm open to PRs on this.