Search code examples
javaandroiddependency-injectionroboguice

Should I inject everything using DI with RoboGuice?


I'm currently developing some App using RoboGuice. My question is: should I realy inject everthing ? Should every class I've created have its own contract interface ?

This question came to my head after my troubles with naming interface for one of my class "BatteryStatusUtil" which returns informations about battery level, and stuff like that. I've read somewhere that "If you cant think name for your interface, you probably don't need interface"

Please correct me if i am using dependency injection too much, or give me some hints on naming my interfaces when I have no "more generic" name for ma interface (like class FastCar with interface Car)


Solution

  • should I realy inject everthing?

    No. Absolutely not. From a dependency injection perspective, there are two kinds of types: newables and injectables.

    If you cant think name for your interface, you probably don't need interface

    That sounds a bit like the Reused Abstraction Principle, although I'm not sure where your quote is coming from. But I would like to rephrase that to:

    If you cant think name for your interface, you probably have to rethink your abstraction.

    For instance, if coming up with a name is hard, you might be violating the SOLID principles.

    And although DI by itself doesn't force you to use interfaces, it is an effective way to keep your code testable. Your BatteryStatusUtil is probably a good example, since this class will probably hook directly into your OS API and to be able to test any consumer of the BatteryStatusUtil you will have to mock that utility class, since you don't want your unit test to take a dependency on your OS and it will otherwise be very hard to simulate the battery status in an automated fashion.