简体   繁体   中英

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.

Personally, I have never used private vals or seen someone use private vals in a data class. 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.

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())
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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