Move mapping functions into different packages/classes
See https://github.com/android/architecture-samples/pull/908#discussion_r1127589401
Problem Mapping functions (e.g., converting TaskEntity ↔ Task ↔ TaskDto) are currently scattered across ViewModels, Repositories, or inlined — leading to:
Harder-to-test code
Tight coupling
Low readability and scalability
Solution: Create a mappers package with clear responsibility Step-by-step Implementation:
- Create a mappers package In your module (e.g., data, domain, or shared), create a new package:
src/ └── main/ └── java/ └── com/example/app/ ├── data/ │ └── mappers/ └── domain/ 2. Create Mapper Classes a. TaskEntityMapper.kt (for DB ↔ Domain)
package com.example.app.data.mappers
import com.example.app.data.local.TaskEntity import com.example.app.domain.model.Task
object TaskEntityMapper {
fun fromEntity(entity: TaskEntity): Task = Task(
id = entity.id,
title = entity.title,
isCompleted = entity.isCompleted
)
fun toEntity(task: Task): TaskEntity = TaskEntity(
id = task.id,
title = task.title,
isCompleted = task.isCompleted
)
} b. TaskDtoMapper.kt (for API ↔ Domain)
package com.example.app.data.mappers
import com.example.app.data.remote.TaskDto import com.example.app.domain.model.Task
object TaskDtoMapper {
fun fromDto(dto: TaskDto): Task = Task(
id = dto.id,
title = dto.title,
isCompleted = dto.done
)
fun toDto(task: Task): TaskDto = TaskDto(
id = task.id,
title = task.title,
done = task.isCompleted
)
} 3. Use in Repository or ViewModel
val task = TaskEntityMapper.fromEntity(taskEntity) val dto = TaskDtoMapper.toDto(task) Bonus: Unit Tests Write testable code in TaskEntityMapperTest.kt:
@Test
fun fromEntity converts correctly() {
val entity = TaskEntity("1", "Test", false)
val task = TaskEntityMapper.fromEntity(entity)
assertEquals("1", task.id)
assertEquals("Test", task.title)
assertFalse(task.isCompleted)
} Final Folder Structure:
data/ ├── local/ │ └── TaskEntity.kt ├── remote/ │ └── TaskDto.kt ├── mappers/ │ ├── TaskEntityMapper.kt │ └── TaskDtoMapper.kt domain/ └── model/ └── Task.kt