I have been learning Dagger 2 for a week and in the tutorials I read, most of them wrote that it is preferable to use Constructor injection over Field and Method injection.
I am confused and wanted to make clear, when should I be using Constructor injection, and when Field and Method injection. Thanks in advance.
I can't say this is the definite answer, but I'd like to share my opinion. I prefer constructor injection because you're forced to create the object by fulfilling its dependencies. In other words you'll never end up in the situation that you call an object's method and because some dependency wasn't set, you get a null pointer exception (unless you set it as null
on purpose in which case you're asking for it). I tend to always use constructor dependency injection everywhere.
That said, sometimes it's simply not possible. In Android for example the Activities are created by the system and hence we don't usually have our own constructor to call and pass in the dependencies. Here I often use field dependency injection. I do this because there's a lot of tools out there that help you out with this.
A third options is through setters
. Personally I never used it. Not entirely sure where this would be needed. Perhaps when the dependency has to change at run time? Not sure.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With