Getters vs. public final fields in records
Andrew Cave
ajcave at google.com
Tue Aug 9 01:09:56 UTC 2022
What is the motivation for defining fields as private and generating
getters in records, as opposed to public fields?
My reason for preferring public fields: Getters for immutable fields
interact poorly with static analysis. e.g. null safety — it is not obvious
that the following is null-safe:
if (r.foo() != null) r.foo().bar();
While the following can be statically deduced as null-safe when foo is a
final field:
if (r.foo != null) r.foo.bar();
I’m sure public final fields open more opportunities for compiler
optimization as well.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://mail.openjdk.org/pipermail/amber-dev/attachments/20220808/1d073d28/attachment.htm>
More information about the amber-dev
mailing list