Getters vs. public final fields in records

Petr Portnov mrjarviscraft at gmail.com
Tue Aug 9 01:16:59 UTC 2022


> I’m sure public final fields open more opportunities for compiler
optimization as well.

AFAIK, the fields of the records are already treated specially[1] (i.e. JVM
treats them as truly final) thus this is somewhat-transitively applied to
trivial getters.

[1]:
https://github.com/openjdk/jdk/blob/master/src/hotspot/share/ci/ciField.cpp#L240

вт, 9 авг. 2022 г. в 04:10, Andrew Cave <ajcave at google.com>:

> 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/20220809/d139cbe2/attachment-0001.htm>


More information about the amber-dev mailing list