Getters vs. public final fields in records

Andrew Cave ajcave at google.com
Tue Aug 9 23:07:35 UTC 2022


> First, I think you have the question backwards: it would be using public
> fields that would require a justification.


This is only true from the perspective of what is currently common practice
in the Java community. But common practice in Java has changed a lot in the
last few decades, often due to what becomes ergonomic with new
project-amber-like features :)

If we look at what record-like things look like in other languages and
settings (C structs, ML records, Pascal records) accessors are the strange
choice that needs justification.

In any case, the answer is simple: not all objects are immutable. If a
> record component were an array, or an ArrayList, or any other object
> with mutable state, having public fields would make it impractical to
> use these types in records in many cases, because we'd be unable to
> expose their state without also exposing their mutability.


I think you are suggesting techniques like explicitly defining accessors
for mutable record components that make defensive copies? Are we really
comfortable calling records “a simple aggregation of values” if I have to
read the documentation or implementation of an accessor just to understand
what the following code does:

someRecord.someArrayComponent()[0] = 42

?
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://mail.openjdk.org/pipermail/amber-dev/attachments/20220809/b244ca98/attachment.htm>


More information about the amber-dev mailing list