On Sunday, November 24, 2013 1:57:26 PM UTC-5, Sam Berlin wrote: > > FWIW, I prefer constructor injection primarily because it guarantees that > it's impossible construct the class w/o all the dependencies. Too many > tests or other pieces of code can fail for "no good reason" if they happen > to construct the class without the right dependencies. Field & method > injection subverts this, so it's easier to construct the class without > everything set. > > "final" is another good reason, but far from the primary reason IMO. >
Another thing final does is communicate very useful information to someone who has to read code someone else wrote. If I'm trying to fix a bug in code I didn't write, I'm going to file away in my head everything I see that is mutable as something I may need to worry about. So, knowing there's this constructor choke-point that is the only place something could be assigned makes it much easier to rule out particular pieces of code as likely to contribute to a problem or not. It's not perfect, but it does help. Sure, somebody can still be injecting a mutable object, but that is a winnable battle using things like ImmutableMap, as Cedric suggests. -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.
