<div dir="ltr"><div dir="ltr">On Thu, Jul 6, 2023 at 7:17 PM Nir Lisker <<a href="mailto:nlisker@gmail.com">nlisker@gmail.com</a>> wrote:</div><div class="gmail_quote"><blockquote class="gmail_quote" style="margin:0px 0px 0px 0.8ex;border-left:1px solid rgb(204,204,204);padding-left:1ex"><div dir="ltr">However, I would like you to consider the following solution.<div>If the method satisfies these conditions:</div><div>1. It is private (and thus final)</div><div>2. It is called only from the/a constructor</div><div>3. It is called only once</div><div>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.</div></div></blockquote><div><br></div><div><div class="gmail_quote"><div><div>Re #2 you would need to say "called only from a constructor that explicitly or implicitly invokes super()"<br></div></div></div><div><br></div></div><div>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.</div><div><br></div><div>In other words, wouldn't doing the following be a pretty close approximation to what you're asking for?</div><br><div><div>class Boat {</div>    final int sails;<div>    Boat(Type type) {</div><div>        this.sails = computeSails(type);<br></div>    }<div>    private static int computeSails(Type type) {</div><div><div>        return switch (type) {</div><div>            case ENGINE -> 0;<br></div><div>            case SAIL -> 2;<br></div><div>            default -> 1;</div><div>        };<br></div></div><div>    }<br></div><div>}</div><div><div><br></div><div>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.<br></div></div></div></div><div><br></div><div>The static analysis would indeed be relatively easy; the "this escape" analyzer does this kind of thing (see ThisEscapeAnalyzer.java).</div><div><br></div><div>Of course there's also the JLS specification work, which can rival the coding work in its complexity...</div><div><br></div><div>-Archie<br></div><br><span class="gmail_signature_prefix">-- </span><br><div dir="ltr" class="gmail_signature">Archie L. Cobbs<br></div></div>