https://kotlinlang.org logo
#dagger
Title
# dagger
c

Colton Idle

12/01/2021, 6:31 PM
In an attempt to hide concrete classes you don't want your team to accidentally use. Which option would you go for? Interface and concrete:
Copy code
interface CrashReporterService {
  fun logFatal(e: Exception)
}

class FirebaseCrashReporterService : CrashReporterService {
  override fun logFatal(e: Exception) {
    // do something
  }
}
Option 1️⃣ :(dont add the concrete to nav graph and just create it at the Provider)
Copy code
@Module
object FirebaseCrashReporterModule {
    
    @JvmStatic
    @Provides
    fun firebaseCrashReporter(dependencies..) : CrashReporter {
        return FirebaseCrashReporter(...)
    }
}
Option 2️⃣: (use a qualifier to make the type "harder" to accidentally use)
Copy code
@Module
@InstallIn(SingletonComponent::class)
abstract class AppInterfaceModule {
  @Singleton
  @Binds
  abstract fun bindsCrashReporterService(
      @Named("placeholder_qualifier") service: FirebaseCrashReporterService
  ): CrashReporterService
}

@Module
@InstallIn(SingletonComponent::class)
class AppImplModule {
  @Singleton
  @Provides
  @Named("placeholder_qualifier")
  fun bindsCrashReporterService(): FirebaseCrashReporterService {
    return FirebaseCrashReporterService()
  }
}
1️⃣ 5
2️⃣ 1
a

ashdavies

12/01/2021, 6:42 PM
Use a factory function to hide the class definition entirely
👍 1
Copy code
interface CrashReporterService {
  fun logFatal(e: Exception)
}

internal class FirebaseCrashReporterService : CrashReporterService {
  override fun logFatal(e: Exception) {
    // do something
  }
}

fun CrashReporterService(): CrashReporterService = FirebaseCrashReporterService()
c

Colton Idle

12/01/2021, 7:03 PM
ooh. Yet another option...
u

ursus

12/01/2021, 11:47 PM
You just moved di code to you business code. Dont do that. do 1 if you do modules, do 2 if you do @inject ctors its a good thing there is a choice, remember
👍 1
3 Views