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

Empty collections by default using RecordInterface

Open JanecekPetr opened this issue 2 years ago • 4 comments

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!

JanecekPetr avatar Apr 05 '23 23:04 JanecekPetr

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

Randgalt avatar Apr 11 '23 08:04 Randgalt

@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.

pawellabaj avatar Jul 04 '23 19:07 pawellabaj

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

Anupam2528 avatar Jul 28 '23 20:07 Anupam2528

I'm open to PRs on this.

Randgalt avatar Aug 02 '23 09:08 Randgalt