On Sunday, November 24, 2013 7:10:15 PM UTC-5, Cédric Beust ♔ wrote:
>
> Have you actually managed to make that program fail? I haven't, even in a 
> very tight loop (which I had to add), and your code doesn't loop, it's just 
> a one time run.
>

I don't think that program is going to do it.

Thinking about it further, I'd say that field injection *is* equivalent to 
constructor injection if the following things are true:
 - You are not giving up any validity checks you would do in the constructor
 - You are nearly-guaranteed that this object can *only* be instantiated by 
dependency injection - something like the package-private FooImpl example I 
gave above (where you'd have to look up the @ImplementedBy annotation, and 
do a bunch of setAccessible() stuff to actually instantiate it - i.e. 
*anybody* would figure out that what they're doing is a really bad idea 
before they finish writing the code to do it)

Otherwise, I have no way to be sure that the object I have actually was 
instantiated via DI and I can trust it is properly initialized.  The thing 
I want is as close to "This object cannot exist unless it is properly 
initialized" as I can get.  Constructor injection and no mutable state gets 
that.  A class which could only reasonably have been instantiated by DI 
gets close enough to that to live with.  An object that might or might not 
have been instantiated by DI but probably was?  That's more uncertainty 
than is really comfortable.  Others may differ.

Nonetheless I don't think I'll ever be able to look at code with fields 
that could be final and aren't, and not mentally give the author a few 
demerits for sloppiness.  That probably just means I've become a curmudgeon 
:-)

There might be a case for final fields in terms of what HotSpot will do 
with them, but much evil code has been written in the name of optimizing 
for whatever that day's version of the VM did with Java code (consider the 
mess in javax.text all built around the assumption that any object 
allocation is expensive; today that guarantees old objects, cache misses 
and more full GCs).  So, tempting though it is, I don't think contorting 
one's code around assumptions about how the VM does things is ever a good 
idea.

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

Reply via email to