How you pass data between modules where they have different models in Clean Architecture?
How you pass data between modules where they have different models in Clean Architecture?
In Clean Architecture, passing data between modules that have different models involves using Data Transfer Objects (DTOs) and mappers to ensure that each layer remains decoupled and adheres to the Dependency Rule. Here’s a detailed explanation of how this can be achieved:
Clean Architecture is structured into several layers, each with its own responsibilities:
DTOs are simple objects used to transfer data between layers without exposing the internal details of the domain entities. They help in maintaining the separation of concerns and ensure that changes in one layer do not affect others.
Mappers are used to convert data from one model to another. Each layer can have its own model, and mappers handle the conversion between these models.
Here’s a step-by-step example of how data can be passed between modules with different models:
data class UserEntity(
val id: String,
val name: String,
val email: String
)
data class User(
val id: String,
val fullName: String,
val emailAddress: String
)
data class UserViewModel(
val id: String,
val displayName: String,
val contactEmail: String
)
class UserEntityToDomainMapper : Mapper<UserEntity, User> {
override fun map(input: UserEntity): User {
return User(
id = input.id,
fullName = input.name,
emailAddress = input.email
)
}
}
class UserDomainToViewModelMapper : Mapper<User, UserViewModel> {
override fun map(input: User): UserViewModel {
return UserViewModel(
id = input.id,
displayName = input.fullName,
contactEmail = input.emailAddress
)
}
}
When data needs to be passed from one layer to another, it is first converted to a DTO, transferred, and then converted back to the appropriate model in the receiving layer.
class GetUserUseCase(
private val userRepository: UserRepository,
private ...
junior
Gợi ý câu hỏi phỏng vấn
Chưa có bình luận nào