Getters vs. public final fields in records

Tagir Valeev amaembo at gmail.com
Tue Aug 9 20:48:40 UTC 2022


Hello!

вт, 9 авг. 2022 г., 03: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();
>

As a developer of IntelliJ IDEA static analyzer, I can assure you that
supporting this case for records (when accessors are not overridden) was a
pretty trivial improvement and took like a couple of hours to implement and
test it. IDEA supports record accessors as well as plain fields. So I
wouldn't buy the static analysis argument.

With best regards,
Tagir Valeev


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


More information about the amber-dev mailing list