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:

    private static final Map<String, String> MAP = Maps.newHashMap();

    public String getValue(String key) {
        synchronized(MAP) {
            if (MAP.isEmpty()) {
                initMap();  // put stuff into MAP
            }
        }
        return MaP.get(key);
    }

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.

 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.
-- 
Cédric

-- 
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.

Reply via email to