Mayokun
Mayokun

Reputation: 63

Android Dependency Injection using Dagger 2

I just started using dagger 2 for dependency injection in android. The way i'm using it now i made sure i don't have

new Class();

but i have a feeling i'm over using dependency injection. I inject any thing that needs an instance. is this right? or are there set of things i can inject or i can inject everything

Upvotes: 1

Views: 280

Answers (1)

Jeff Bowman
Jeff Bowman

Reputation: 95714

It is very easy and common to overuse dependency injection, and I wouldn't endorse the practice of "inject anything that needs an instance". However, you'll need to decide which aspects fall into which group.

One distinction I've seen drawn is "injectables" vs "newables", as in this oft-cited article by Miško Hevery (also on the Google Testing Blog), this article by Giorgio Sironi, and this Dagger 2 StackOverflow answer.

You may want to weigh the advantages of dependency injection, which include:

  • ability for the environment to substitute out implementations, particularly in testing against unwritten, heavy, or nondeterministic implementations
  • insulation from your dependencies' dependencies, which may change and evolve independently

...against the costs, which include:

  • difficulty in telling which implementation may be supplied
  • additional Provider classes and instances, which may be expensive on embedded/mobile platforms
  • complex syntax and build steps to handle mixing constructor parameters and factories, such as through AutoFactory

Value and model objects, which are unlikely to have multiple or risky implementations, are often squarely in the newable camp; interconnected and interdependent services are often far into the injectable camp. For lightweight services and utils, you'll need to identify the benefits provided above and draw the line based on the benefits you need.

Upvotes: 1

Related Questions