Junior — Middle
Do you use an interface for implementing the repository or create it directly?
sobes.tech AI
Answer from AI
To implement a repository in Android, it is usually recommended to use an interface. This allows separating the contract (what the repository should do) from the specific implementation, which makes testing, replacing the implementation, and maintaining the code easier.
For example, you can declare an interface:
interface UserRepository {
suspend fun getUser(id: String): User
suspend fun saveUser(user: User)
}
And then implement it in a class:
class UserRepositoryImpl(private val api: UserApi, private val dao: UserDao) : UserRepository {
override suspend fun getUser(id: String): User {
// implementation
}
override suspend fun saveUser(user: User) {
// implementation
}
}
This approach improves modularity and allows easy substitution of implementations, for example, for testing or when changing the data source.