简体   繁体   English

在数据类主构造函数中使用私有字段是一种好习惯吗?

[英]Is it good practice to use private fields in data class primary constructor?

I want to write code so that it makes sense to everyone and follows by experts so I want to know Is it good to make data class fields private and only let them access by public fields by performing some operation .我想编写代码,使其对每个人都有意义并由专家跟随,所以我想知道将数据类字段设为私有并仅通过执行某些操作让它们通过公共字段访问是否好 I have added an example below to explain my question.我在下面添加了一个示例来解释我的问题。 I know I can make fields private and the compiler will be okay with that.我知道我可以将字段设为私有,编译器会同意的。 I am asking this question because I have seen data class with public fields only and my project requires performing some operations on fields before we can access them so to achieve this I have made them private like the below example but now I am thinking is it a good practice or I can do something best.我问这个问题是因为我见过只有公共字段的数据类,我的项目需要在我们访问它们之前对字段执行一些操作,因此为了实现这一点,我已经将它们设为私有,如下例所示,但现在我在想这是一个好的做法,否则我可以做得最好。

data class BatteryDemo(
    private val _level: Int,
    private val _temperature: Int,
    private val _voltage: Int,
) {
    val level get() = _level.toString()
    val temperature get() = _temperature.toString()
    val voltage get() = _voltage.toString()

}

Well you can do it if you want or have a compelling use-case.好吧,如果您愿意或有一个引人注目的用例,您可以这样做。 A lot of Kotlin's newer features that Java doesn't have yield questions in how exactly we should use them because there aren't long established industry patterns for them.很多 Kotlin 的 Java 新特性没有产生关于我们应该如何使用它们的问题,因为它们并没有长期建立的行业模式。

Personally, I have never used private vals or seen someone use private vals in a data class.就我个人而言,我从未使用过私有 val,也从未见过有人在数据类中使用过私有 val。 And it does break destructuring outside of the class, if you care, so you won't be able to do val (level, temperature, voltage) = batteryDemo with private fields.如果您关心,它确实会破坏课堂之外的解构,因此您将无法使用私有字段执行val (level, temperature, voltage) = batteryDemo

Some possible alternatives:一些可能的替代方案:

// Secondary Constructor

data class BatteryDemo(
    val level: String,
    val temperature: String,
    val voltage: String,
) {
    constructor(level: Int, temperature: Int, voltage: Int) : this(level.toString(), temperature.toString(), voltage.toString())
}

// Creation function

data class BatteryDemo(
    val level: String,
    val temperature: String,
    val voltage: String,
) {
    companion object {
        fun newInstance(level: Int, temperature: Int, voltage: Int): BatteryDemo {
            return BatteryDemo(level.toString(), temperature.toString(), voltage.toString())
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM