Sobes.tech
Junior — Middle

In which cases is it preferable to use @Provides instead of @Binds, and why is it not recommended to completely abandon @Provides?

sobes.tech AI

Answer from AI

In Dagger (Android), @Provides and @Binds are annotations for defining how dependencies are provided, but they are used in different cases:

  • @Binds is used to bind an interface to a specific implementation. It requires an abstract method and only works with existing objects (e.g., classes with an @Inject constructor). This is a more efficient and concise way, as it does not generate additional code.

  • @Provides is used when you need to explicitly create an object, especially if creation is complex, requires logic, parameters, or cannot be done through an @Inject constructor. A method with @Provides can contain arbitrary code.

Why you shouldn't completely abandon @Provides:

  • Not all dependencies can be created via @Inject constructor or @Binds.
  • Sometimes additional creation logic, configuration, or runtime selection of implementation is needed.

Example:

@Module
abstract class MyModule {
    @Binds
    abstract MyInterface bindMyInterface(MyImplementation impl);

    @Provides
    static MyObject provideMyObject(Dependency dep) {
        // complex creation logic
        return new MyObject(dep.getConfig());
    }
}

In summary, @Binds is preferred for simple interface-to-implementation binding, while @Provides is for more complex object creation. Completely abandoning @Provides limits module flexibility.