Use Dagger `Qualifier` instead of `Named`
See original GitHub issueProblem
Currently, we are using Named
annotation to define dependencies that have same return types.
@Provides
@Named("full_date")
fun provideDateFormatterForFullDate(locale: Locale): DateTimeFormatter = DateTimeFormatter.ofPattern("d-MMM-yyyy", locale)
@Provides
@Named("date_for_user_input")
fun provideDateFormatterForUserInput(locale: Locale): DateTimeFormatter = DateTimeFormatter.ofPattern("dd/MM/yyyy", locale)
This is problematic because it is not type-safe, a developer can find the issue once they build the project.
Proposal 1
We can define Qualifier
s for the different dependencies and use those.
@Qualifier
@Retention(AnnotationRetention.SOURCE)
annotation class FullDate
Then while providing & injecting the dependencies we can Qualifier
instead of Named
@Provides
@FullDate
fun provideDateFormatterForFullDate(locale: Locale): DateTimeFormatter = DateTimeFormatter.ofPattern("d-MMM-yyyy", locale)
@field:[Inject FullDate]
lateinit var dateFormatter: DateTimeFormatter
This will allow us to be more type-safe when providing and injecting our dependencies. There is no additional overhead, Named
itself is a Qualifier
so they both behave the same way.
Problems
- With this approach, we have to define
Qualifier
for every dependency. I feel like this will increase the amount of code we have to maintain.
Proposal 2
While proposal 1 is the preferred approach, I can understand that we have to define new annotations every time there is a new dependency with the same return type as an already defined dependency. So the easiest approach to make sure using @Named
is safe is to define a variable inside Object
with the name of the dependency to make sure it’s same across all usages.
object DepsNames {
const val FULL_DATE = "full_date"
}
@Provides
@Named(FULL_DATE)
fun provideDateFormatterForFullDate(locale: Locale): DateTimeFormatter = DateTimeFormatter.ofPattern("d-MMM-yyyy", locale)
So, what does everyone think? Is it something we should look into? Any other ideas?
Issue Analytics
- State:
- Created 3 years ago
- Comments:5 (4 by maintainers)
Top GitHub Comments
Qualifier Proposal +1
Yes, it will behave the same way
Named
behaves so it should not affect our builds anymore thanNamed
.