Queries about records

Remi Forax forax at univ-mlv.fr
Wed Dec 23 23:30:00 UTC 2020


----- Mail original -----
> De: "Vikram Bakshi" <vab2048 at gmail.com>
> À: "amber-dev" <amber-dev at openjdk.java.net>
> Envoyé: Mercredi 23 Décembre 2020 17:58:25
> Objet: Queries about records

> Hello,

Hi,

> 
> I have a number of queries about the new Java record feature.
> 
> 1. What exactly is the reason that the canonical constructor must have the
> same access as the record?
> 
> Consider the following use case: the record is intended to be a dumb-data
> carrier of its validated fields but the validation cannot take place in the
> record's constructor because we require access to some elaborate validator
> objects to actually perform the validation.
> 
> So I thought a way to solve this would be to create the record as public
> and the canonical constructor as package-private. Then we have a record
> 'factory' in the same package which performs the actual validation and
> creation of the record. However this is not allowed currently because it
> violates the constraint that the canonical constructor must have the same
> access as the record itself.
> 
> I was just wondering why this constraint?

Records are named tuples, they are defined only by their components, in a transparent manner i.e. no encapsulation.
>From a tuple, you can access to the value of each component and from all component values, you can create a tuple.
The idea is that, in a method, if you are able to see a record, you can create it. Thus the canonical constructor has the same visibility as the record itself.

Being able to de-construct/re-construct a record allows to transform any data text/binary representation (think JSON by example) from/to a record/list of record.

> 
> 2. Is there a shorthand to declaring a record field must be non-null?
> 
> So for the case where we do not want to allow null in a record field we
> have to implement our own logic in the canonical constructor and call
> `Objects.requireNonNull(...)`. Is there a way to declare in the record
> signature itself that we want it to be non-null to avoid this boilerplate?

No, if we introduce a shorthand for avoiding the requireNonNull(), it will be something global to all/most of the types in Java, not just for record components.

> 
> 3. What exactly is the difference between a static record and non-static
> record ?
> 
> I find myself creating a whole bunch of public records within a single
> class. Is there actually any need to mark them as static?

There are no difference, records are always static otherwise it means that a record would have access to the enclosing values so it would not be defined only by its components.

> 
> Thanks very much for creating records - they make coding a lot more fun and
> allow for writing much more beautiful Java.
> 
> Regards,
> vab2048

regards,
Rémi


More information about the amber-dev mailing list