>From a human-oriented perspective an advantage of final fields that are
initialized in the constructor is that we eliminate bugs like:
class Foo {
@Inject private Bar bar;
@NonNull private Baz baz;
void doFoo() {
return baz.do() + bar.do();
}
}
In other words, there is a very real human element around having the
compiler guarantee fields are assigned.
I'm also generally wary of the testability of field injection. At some
point if you instantiate the class under test directly in a unit test,
you'll likely want to assign values to the fields. This requires removing
the "private" qualifier. At this point the comparison is "private final"
versus "<package>", and I like "private final" as the better visibility
option.
On the flip side, yes, I agree brevity of field injection is enticing,
especially in a class hierarchy! But nonetheless I like the trade-off of
getting a bit more security with the more verbose constructor injection.
Fred
On Sun, Nov 24, 2013 at 4:06 PM, Cédric Beust ♔ <[email protected]> wrote:
>
> On Sun, Nov 24, 2013 at 11:50 AM, Tim Peierls <[email protected]> wrote:
>
>> 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).
>
>
> Understood, and my point was that these reasons are overstated.
>
> Let's be concrete: can you write a program that gets initialized correctly
> with constructor injection and incorrectly with field injection? I've tried
> to come up with one with various techniques (misusing volatile,
> synchronized, the doubly locked idiom, etc...) but I've never been able to
> come up with one. My gut feeling right now is that it can't be done on X86.
>
> Happy and excited to be proven wrong.
>
> --
> 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.
>
--
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.