Re: Records — Dealing with nullable values
Remi Forax
forax at univ-mlv.fr
Sat Dec 14 22:53:44 UTC 2019
Hi Arash,
in your example, you want gender to be Optional in term of API but stored as null in term of implementation.
Records only supports to have the same API internally and externally.
so either you declare gender as Optional<Gender> or you use a class instead of a record because you want a clean separation between the public API and the private implementation.
regards,
Rémi
----- Mail original -----
> De: "Arash Shahkar" <arash.shahkar at gmail.com>
> À: "amber-dev" <amber-dev at openjdk.java.net>
> Envoyé: Samedi 14 Décembre 2019 23:01:09
> Objet: Records — Dealing with nullable values
> Hi,
>
> I’ve been using Lombok for quite a while now to automatically generate
> boilerplate code for "data carrier" classes. However, a pattern I really like
> and have found to work very well is to verify non-nullity of all the fields
> that must not be null, and return an Optional<Field> from the accessor of a
> field if it’s allowed to have a null value. Consider:
>
> @lombok.Value
> class Person {
>
> String name;
> Gender gender;
>
> Person(String name, Gender gender) { … } // customize the constructor, verifying
> that name is defined and valid
>
> Optional<Gender> getGender() { // customize the accessor for gender, to make
> sure calling code deals with the possibility of gender being null
> return ofNullable(gender);
> }
> }
>
> Doing a similar thing with records is not possible, due to the fact that the
> accessor for gender has to exactly return a Gender. With the current
> specification for records, the only option is to do:
>
> record Person(String name, Optional<Gender> gender) {
> …
> }
>
> Is this considered good practice? Do you suggest any alternatives?
More information about the amber-dev
mailing list