oop - Kotlin setter 打破封装
问题描述
我一直很担心这种实现
var stringRepresentation: String
get() = this.toString()
set(value) {
setDataFromString(value) // parses the string and assigns values to other properties
}
对我来说,它需要确定谁在分配值,因为局外人并不期望在类中出现这种行为,只想为该字段设置一个值。
在这种情况下,我宁愿调用一个函数来分配值,而另一个函数来调用需要调用的函数。或者只是调用一个具有好名称的函数来更改值并执行所需的操作。
这种实现方式危险吗,不违反封装规则吗?
谢谢
解决方案
用例的实现似乎不寻常且危险,因为在字段上调用 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", ...)
}
推荐阅读
- php - 在不丢失中间件值的情况下获得预期的目标 URL
- javascript - 显示每个相册的所有照片后换行
- html - 如何将焦点设置在动态 FormArray 的第一个表单控件上?
- mod-rewrite - 用 if-not Condition 重写 Condition
- python - pybedtools bam_to_bed() 床
- java - 使用 maven-antrun-plugin 从类路径读取文件
- mono - 无论如何更新IL指令以使用新的局部变量索引?
- mysql - 有没有更好的方法在 sql 中编写 REGEXP 来选择唯一的事务号 R-0001 和 R-AD-0001
- javascript - 如何传递从 django 表单操作 url 的下拉列表中选择的项目的 id?
- python - 在父类中为返回任何子类对象的方法键入提示