On Sun, Nov 24, 2013 at 2:20 PM, Cédric Beust ♔ <[email protected]> wrote:
> On Sun, Nov 24, 2013 at 10:57 AM, Tim Peierls <[email protected]> wrote: > > On Sun, Nov 24, 2013 at 1:24 PM, Cédric Beust ♔ <[email protected]> wrote: >> >>> I would be totally on board with constructor injection if finalguaranteed >>> structural immutability, but all it does is guarantee reference >>> immutability (“this field is only assigned once”), ... >>> >> That's *not* all it does. Final fields provide additional safety >> guarantees even in the presence of data races involving a reference to the >> containing object: As long as that reference isn't leaked during >> construction, the final fields *and everything reachable through them*are >> guaranteed to be properly constructed. >> > That’s not quite true. For example, the following is absolutely not thread > safe: [...code...] This is just an extension of my earlier point that all > final does is guarantee immutability of reference, which really doesn’t > buy you that much in practice. > The safety guarantees for final (instance) fields that I described have nothing to do with immutability, and the example you gave with a *static* final field does not illustrate those guarantees in action. My point was that there are reasons to prefer final fields beyond the desire for immutability (which, as you correctly pointed out, final fields alone don't guarantee). That, on top of all the other good reasons given in this thread, is why I prefer constructor injection: It's the only way to inject objects that enjoy those additional (albeit limited) safety guarantees. > > But I think the other argument that Tim (other Tim!) advanced is more >> important: In addition to providing those guarantees, final clearly >> declares your intent. >> > I think the intent “I won’t reassign this variable” is pretty much > implied for most code in Java, I hardly ever see anyone do that in > practice, even when they could (e.g. non final parameters). It’s widely > considered a code smell that won’t pass code review to reassign variables. > Sounds like you've drifted away from the use of final with fields, which is not related to the use of final with variables. It's hard to define mutable objects without being able to assign new values to fields. --tim -- You received this message because you are subscribed to the Google Groups "google-guice" group. To unsubscribe from this group and stop receiving emails from it, send an email to [email protected]. To post to this group, send email to [email protected]. Visit this group at http://groups.google.com/group/google-guice. For more options, visit https://groups.google.com/groups/opt_out.
