Getters vs. public final fields in records
Brian Goetz
brian.goetz at oracle.com
Tue Aug 9 13:13:24 UTC 2022
> What is the motivation for defining fields as private and generating
> getters in records, as opposed to public fields?
First, I think you have the question backwards: it would be using public
fields that would require a justification.
We did consider this briefly during the design process, and realized
this would be a terrible idea.
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.
> 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 sympathize; null safety is difficult to verify. But that's no reason
to undermine another feature just to make an already-bad problem a few
percent better.
> I’m sure public final fields open more opportunities for compiler
> optimization as well.
Don't be so sure! Getters are almost always inlined. (Inlining is
usually a time-space tradeoff, but for methods as small as getters, it
is a win on both time and space, so will almost always be taken.)
More information about the amber-dev
mailing list