1

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

3
  • You should not be inject everything, first thing you have to consider is , do you have 3rd party dependencies and how often you use them. Commented Apr 25, 2017 at 8:33
  • well yeah most new Class() can be replaced with an unscoped provider method in a module. Commented Apr 25, 2017 at 11:36
  • if you're trying to win an injecting contest you might be on the right track Commented Apr 25, 2017 at 12:24

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.