Search code examples
javaandroidsingletondaggerotto

Why do we need Dependency Injection for singleton classes in java or Android?


For example if I am injecting (Otto)Bus object, using Dagger, then i would have to write more line of code just to specify, at how many places I'm injecting it, in the interface.

On the other hand if I just use a singleton class to return Bus instance then I need not write as many lines of code as I would have to in case of Dependency injection.

So my question is "Why or how is it better to use Dependency Injection to inject Singleton class instances?"


Solution

  • First, DI will reduce the amount of boilerplate you have to call to setup your instances with the required dependencies. Less code means improved readability. The price to pay for this is the configuration involved, but, for large scale projects, it's worth it.

    Second, you can benefit from DI when you are running automated tests on your app. You will have the power to replace the standard singleton implementation with a mock, that you can control and use to simulate the different scenarios, needed to cover all cases.

    Having said that, I also think that DI is only a good fit for large scale Android projects, or medium to large scale EE projects. Otherwise it adds a bit of unwanted complexity IMHO.