简体   繁体   中英

How to handle a dependency with multiple other dependeccies in dagger?

I am currently introducing dagger into an android application. I am a bit worried with a design aspect and I am wondering whether there is a better way to handle it. Let us use the example provided here to illustrate the question. Consider the following module;

@Module
class DripCoffeeModule {
  @Provides Heater provideHeater() {
    return new ElectricHeater();
  }

  @Provides Pump providePump(Thermosiphon pump) {
    return pump;
  }
}

Here, it is easy to see that the creation of a pump depends on a Thermosiphon and because of that, it is provided as an arg in the providePump method. likewise, if we wanted the DripCoffeeModule Module to be able to provide an object of type C whose dependencies where a Heater and a Pump , we'd have the following method:

@Provides
C provideC(Heater heater, Pump pump){
  C wantedC = applyMagic(heater, pump)
  return c
}

If the provideC method had 16 (or any large number of) dependencies, would it have 16 or more args? Is there no better way of handle such cases?

In that case I'd argue your design of C is flawed. From the IntelliJ IDEA Code Inspections List :

Overly Coupled Class
This inspection reports any instances of classes which are highly coupled, ie that reference too many other classes. Classes with too high a coupling can be very fragile, and should probably be broken up.

Thus, you don't want to have 16 dependencies for your C class, but you want ~2-3-4 dependencies for it, which in turn depend on a small number of classes.


If you really want a lot of dependencies, you can annotate the constructor with @Inject . Then the @Provides C provideC(...) method is not necessary:

public class C {

  @Inject
  public C(Object arg1, Object arg2, Object arg3, ...) { /* ... */ }

  /* ... */
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM