【问题标题】:What are the best practices to unify access to data classes properties统一访问数据类属性的最佳实践是什么
【发布时间】:2021-05-28 22:27:27
【问题描述】:

我有一个类 ExpenseDto

data class ExpenseDto(
    val id: Int,
    val name: String,
    val aggregationA: ExpenseAggregationA,
    val aggregationB: ExpenseAggregationB,
    val aggregationC: ExpenseAggregationC,
)

并且它的所有关联都具有相同的字段。在这里可以应用哪些最佳实践来普遍化它

data class ExpenseAggregationA(
    val id: Int,
    val text: String? = null
)

data class ExpenseAggregationB(
    val id: Int,
    val text: String? = null
)

data class ExpenseAggregationC(
    val id: Int,
    val text: String? = null
)

【问题讨论】:

  • 你不能只使用1个数据类ExpenseAggregation吗?还是您希望类型分开?
  • 我需要将类型分开,因为它们与不同的模式有关系

标签: oop kotlin generics inheritance


【解决方案1】:

data classes 可以从 sealed class 继承。

sealed class ExpenseAggParent (val id: Int, val text: String? = null) {
    data class ExpAggA( override val id: Int, override ...)
    data class ...
    data class ...
}

除此之外,有时我喜欢使用“属性统一器”接口,尤其是在重构具有相同语义但属性名称不同的类的遗留代码时:

interface HasId(val id: Int)

data class ExpenseAggregationX(
   override val id: Int,
   ...
): HasId

data class ExpenseAggregationY: HasId {

   val someOtherNameButStillId: Int

   override val id: Int
       get() = this.someOtherNameButStillId
}

当然,您可以使用良好的旧界面,但为此,您可以重复使用上述方法:

interface ExpenseAggregation: HasId, HasText

data class ExpenseAggregationA(
    override val id: Int,
    ...
): ExpenseAggregation

// Other approach for classes with other existing names, see above
data class ExpenseAggregationB: ExpenseAggregation {
    ...
}

这接近于 Kotlin 目前不直接支持的混合方法,但为了完整性,there are delegations 如果您的类是服务而不是 DTO 时可用。

【讨论】:

    猜你喜欢
    • 2010-10-30
    • 2015-09-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多