It seems like a very simple and trivial question, but how do you deal with data classes where the attributes can change over time? I know data classes should only contain immutable attributes, but what to do if it's necessary that they are mutable.
The Todo data class reflects an entry in a todo list. As such an entry can be reformulated or change from "not done" to "done", the values must or should be changeable. How would such a thing be handled correctly?
First Approach: Values are declared as var and are publicly accessible. The values are changed directly by another class
data class Todo (
var description: String,
var isDone: Boolean
)
class TodoList (
val entries: MutableList<Todo> = mutableListOf()
) {
fun setTodoDone(entry: Todo) { entries[entries.indexOf(entry)].isDone = true }
fun updateDesc(entry: Todo, desc: String) {
entries[entries.indexOf(entry)].description = desc
}
}
Second Approach: Values are assigned during initialisation. The values cannot be accessed directly, but are accessed via backing properties. Changes to the values are monitored by calling corresponding methods within the data class.
data class Todo2 (
private var _description: String,
private var _isDone: Boolean
) {
val description: String
get() = _description
val isDone: Boolean
get() = _isDone
fun setDone() { _isDone = true }
fun updateDescription(desc: String) { _description = desc }
}
class TodoList2 (
val entries: MutableList<Todo2> = mutableListOf()
) {
fun setTodoDone(entry: Todo2) = entry.setDone()
fun updateDesc(entry: Todo2, desc: String) = entry.updateDescription(desc)
}
Third Approach: The values of the data class remain unchanged. Changes to the entries are made via a copy of the entries, which are saved in modified form.
data class Todo3 (
val description: String,
val isDone: Boolean
)
class TodoList3 (
val entries: MutableList<Todo3> = mutableListOf()
) {
fun setTodoDone(entry: Todo3) {
entries[entries.indexOf(entry)] = entry.copy(isDone = true)
}
fun updateDesc(entry: Todo3, desc: String) {
entries[entries.indexOf(entry)] = entry.copy(description = desc)
}
}
Is one of this approaches correct, or should such a problem be solved a completelly other way like using a normal class instad of a data class? Thaks for your reply :-D