Java 14 records canonical constructor
Christian Beikov
christian.beikov at gmail.com
Thu Jun 4 17:53:15 UTC 2020
Hello,
I recently found out that a record constructor can set the record
components explicitly and was kind of surprised. I thought that a record
is a plain data carrier and that I can re-construct a record object from
it's components, but this is not guaranteed.
Here a quick example:
public record UserRecord(Integer id, String userName) {
public UserRecord {
if (Character.isUpperCase(userName.charAt(0))) {
this.userName = null;
} else {
this.userName = userName.toUpperCase();
}
}
}
IMO setting a field/record component directly should be prohibited. A
developer should move such a logic to a static method or a different
constructor. The canonical record constructor should only do sanity
checks i.e. argument is not-null, not blank etc. but not alter the
arguments or set the fields manually. It's ok for an additional
non-canonical constructor to alter the arguments though.
What do you think? Was that an oversight or is this intended? If it is
intended, what is the reasoning for allowing this?
I don't have a problem with this behavior. I just wouldn't have expected
it. If I remember correctly, there were some talks about de-construction
patterns at conferences that pointed out, that being able to
re-construct a record from the component state is a vital property of
records.
Regards,
Christian
More information about the amber-dev
mailing list