【发布时间】:2021-06-08 17:38:17
【问题描述】:
我正在尝试使用 Kotlin 实现干净的架构。流程将是:
usecase --> get rowresult from DB --> map rowresult to entity --> entity used by the usecase to check business rules
代码示例:
UserTable
------------------
id (varchar)
email (varchar)
password (varchar)
gender (varchar)
phone (varchar)
anotherAttribute1
anotherAttribute2
.
anotherAttributeN
class UserEntity {
val id: String,
val email: String,
val password: String,
//Business rules
fun isUserAllowedToLogin(): Boolean {
//validate password
}
}
interface UserDataStore {
fun getUser(email: String): User
}
class UserDataStoreImplementation {
fun getUser(email: String): User {
//query to DB
val resultRow = db.query("SELECT id, email, password from UserTable where email=${email}")
//map to UserEntity
val user: UserEntity = Mapper.toUserEntity(userResultRow)
return user
}
}
class LoginUseCase {
fun execute(emailInput: String, passwordInput: String): Boolean {
val user = UserDataStore().getUser(emailInput)
if (!user.isUserAllowedToLogin) {
//do something
}
return result
}
}
请注意 loginUseCase 使用的唯一属性是用户电子邮件和密码。
问题 1. 假设如果我有另一个 UseCase (GetUserFullDetailAndStaffDetail Usecase) 将使用更复杂的 User 属性,我应该对 GetUserFullDetailAndStaffDetail 用例使用相同的 UserEntity 吗?所以 UserEntity 将是:
class UserEntity {
val id: String,
val email: String,
val password: String,
val gender: String,
val phone: String,
//more attributes
.
.
//more complex object
val Staff: Staff
fun isUserAllowedToLogin(): Boolean {
//validate password
}
fun checkStaffStatus(): Boolean {
//do something
}
}
class UserDataStoreImplementation {
fun getUser(email: String): User {
//query from DB which will have a lot of attributes
val resultRow = db.query("SELECT * from UserTable where email=${email}")
//map to UserEntity
val user: UserEntity = Mapper.toUserEntity(userResultRow)
}
}
如果我使用不同的实体,它将违反 DRY 原则(在 UserDataStoreImplementation 中重复 UserEntity 和重复 getUser 方法),但如果我对 GetUserFullDetailAndStaffDetail 用例使用相同的 UserEntity,则在 UserDataStoreImplementation 中为 LoginUseCase 的 getUser 必须获得无用的完整属性。
问题2. UserDataStoreImplementation 中的getUser 是否应该有不同的方法(一种会在UserTable 中为LoginUseCase 返回部分属性,另一种会在UserTable 中为GetUserFullDetailAndStaffDetail UseCase 返回完整属性)?
【问题讨论】:
标签: architecture software-design clean-architecture