<div dir="ltr">> I’m sure public final fields open more opportunities for compiler optimization as well.<div><br></div><div>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.</div><div><br></div><div>[1]: <a href="https://github.com/openjdk/jdk/blob/master/src/hotspot/share/ci/ciField.cpp#L240">https://github.com/openjdk/jdk/blob/master/src/hotspot/share/ci/ciField.cpp#L240</a></div></div><br><div class="gmail_quote"><div dir="ltr" class="gmail_attr">вт, 9 авг. 2022 г. в 04:10, Andrew Cave <<a href="mailto:ajcave@google.com">ajcave@google.com</a>>:<br></div><blockquote class="gmail_quote" style="margin:0px 0px 0px 0.8ex;border-left:1px solid rgb(204,204,204);padding-left:1ex">What is the motivation for defining fields as private and generating getters in records, as opposed to public fields?<div dir="auto"><br></div><div dir="auto">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:</div><div dir="auto"><br></div><div dir="auto">if (r.foo() != null) r.foo().bar();</div><div dir="auto"><br></div><div dir="auto">While the following can be statically deduced as null-safe when foo is a final field:</div><div dir="auto"><br></div><div dir="auto">if (r.foo != null) r.foo.bar();</div><div dir="auto"><br></div><div dir="auto">I’m sure public final fields open more opportunities for compiler optimization as well.</div>
</blockquote></div>