This is a question on UseCase in the Domain Layer....
# android-architecture
v
This is a question on UseCase in the Domain Layer. The article discourages using
Util
classes and putting shared logic in the domain layer as UseCases. If that's the case, can I use
object
s as a UseCase, for example:
Copy code
// domain/GetTimeAgoUseCase.kt

object GetTimeAgoUseCase {
   operator fun invoke(time: Long){
     // return "a week"
   }
}
..and use it in my UI layer like this:
Copy code
class HomeViewModel: ViewModel(){
   
   fun getTime(): String = GetTimeAgoUseCase(item.timestamp)

}
..or..
Copy code
@Composable
fun ListItem(item){
   Text("Posted ${ GetTimeAgoUseCase(item.timestamp) } ago")
}
c
If it works for you - why not? However, do note that an
object
cannot have constructor parameters so this pattern has very limited applicability. Depending on how consistent you want to be, you might want to abandon the
object
in favor of a regular class and inject it into your ViewModel as a factory. Personally I would not call a usecase from a
Composable
. A UseCase should be called from a
ViewModel
or from another
UseCase
. Finally - while I agree with the architecture recommendation, I disagree with the example that is chosen.
FormatDateUseCase
should not be a UseCase at all. I view formatting as a presentation concern and not a business concern. It belongs firmly in the UI layer.
v
When injecting a regular class UseCase into the VM, I will have to create another model that includes the "time ago" data along with the original model coming from the Data layer. So I thought of using it directly within Composables, but didn't want to create instances on every recomposition. So my idea was to make the UC an
object
but wanted to check if that's a good pattern.
On the disagreement that
FormatDateUseCase
not being a UseCase, the article shows this example, and highlights that whatever we used to put in Util classes before should be moved to UseCases. So that creates the confusion - whether to keep those silly utility functions inside the ui/util package, (so that it won't be accessed by the Data/Domain layers) or to make them UseCases.