首页 > 解决方案 > Kotlin setter 打破封装

问题描述

我一直很担心这种实现

var stringRepresentation: String
    get() = this.toString()
    set(value) {
        setDataFromString(value) // parses the string and assigns values to other properties
    }

对我来说,它需要确定谁在分配值,因为局外人并不期望在类中出现这种行为,只想为该字段设置一个值。

在这种情况下,我宁愿调用一个函数来分配值,而另一个函数来调用需要调用的函数。或者只是调用一个具有好名称的函数来更改值并执行所需的操作。

这种实现方式危险吗,不违反封装规则吗?

谢谢

标签: oopkotlin

解决方案


用例的实现似乎不寻常且危险,因为在字段上调用 ​​setter 时,我永远不会想到以下行为:

为其他属性赋值


我建议创建单独的函数。

1)无论如何,您的字段是一个函数:

fun stringRepresentation() = this.toString()

2)设置其他属性:

parseAndSetOther(value: String)  { 
  /* parses the string and assigns values to other properties */ 
}

2.1)也许你可以保持对象不可变并返回一个新的 - 修改后的对象:

parseAndSetOther(value: String) : MyClass { 
  /* parses the string and assigns values to other properties */ 
  return this.copy(value = "new value", ...)
}

推荐阅读