1

I have been learning Dagger 2 with Android. Most of the posts I read 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 use Constructor injection, and when Field and Method injection?

CJ Dennis
  • 4,226
  • 2
  • 40
  • 69

2 Answers2

1

I think rule of thumb is to use field injection only for framework classes that are instantiated by the system rather than the developer : Activity Fragment and so on (because you cannot lets say instantiate an Activityyourself).

Use constructor injection for everything else, one of the benefits why constructor injection is preferred is that its much easier to work with for unit testing - you can still instantiate your class "manually" with that constructor.

At least for me, constructor injection feels more "natural"/ more object oriented - dependencies are passed in constructor and its up to the class to deal with them how it wants, field injection is like someone from outside comes and "shoves" these dependencies in the injected class

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
estn
  • 1,203
  • 1
  • 12
  • 25
1

Injection by a constructor is more readable and you can easily distinguish the part of a class that is connected with dependency injection from the rest. Secondly, all the values are initialized from the very beginning of the existence of the class so you can use them for eg in initialization blocks.

The tests are cleaner, you exactly know what dependencies you should provide for the class under test or your code won't compile. With field injection, you need to set everything manually.

But all of that doesn't mean that there aren't use cases for field or method injection. Field injection is especially useful in android classes for which you don't have control over instantiation like Activity.

I tend to use field injection also in superclasses for which children I use constructor injection and I don't want to pollute constructors with common objects. Eg. I have BaseViewModel in which I inject ExceptionHandler on the field, this way I don't need to put that ExceptionHandler in every child class constructor and then pass upwards to the base.

Filip P.
  • 1,194
  • 1
  • 7
  • 18