Assignment of final fields outside of constructors
Archie Cobbs
archie.cobbs at gmail.com
Fri Jul 7 01:59:06 UTC 2023
On Thu, Jul 6, 2023 at 7:17 PM Nir Lisker <nlisker at gmail.com> wrote:
> However, I would like you to consider the following solution.
> If the method satisfies these conditions:
> 1. It is private (and thus final)
> 2. It is called only from the/a constructor
> 3. It is called only once
> then it may assign final fields. The last condition might not be strictly
> necessary because there is already a check if the final field has been
> assigned already. These conditions can be applied recursively, checking if
> the call originates in the constructor and allowing to further divide
> the constructors into sub-steps, but I'm willing to wait with this addition.
>
Re #2 you would need to say "called only from a constructor that explicitly
or implicitly invokes super()"
Playing devil's advocate for a moment - it's not really the field
assignment that is the bulky problem, it's the calculation that computes
the field's value.
In other words, wouldn't doing the following be a pretty close
approximation to what you're asking for?
class Boat {
final int sails;
Boat(Type type) {
this.sails = computeSails(type);
}
private static int computeSails(Type type) {
return switch (type) {
case ENGINE -> 0;
case SAIL -> 2;
default -> 1;
};
}
}
The only difference is where the "this.sails = " part lives. Of course this
approach doesn't work quite as well when you want to compute multiple final
field values in one private method - then you'd need to return them in some
carrier object, etc.
The static analysis would indeed be relatively easy; the "this escape"
analyzer does this kind of thing (see ThisEscapeAnalyzer.java).
Of course there's also the JLS specification work, which can rival the
coding work in its complexity...
-Archie
--
Archie L. Cobbs
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://mail.openjdk.org/pipermail/amber-dev/attachments/20230706/6d867095/attachment-0001.htm>
More information about the amber-dev
mailing list