https://kotlinlang.org logo
Title
i

igor.wojda

03/04/2023, 8:21 AM
I need a bit of help with data modeling. I have an object with a few properties that represent the task:
class Task(
    val id: Int,
    val name: String,
    val dueDate: String,
    val priority: Int,
    ...
)
Now user can modify each of the task properties. I would like to store an activity/change log containing all of the modifications e.g: - task name changed from "oldValue" to "newValue" - task priority changed from "oldValue" to "newValue" - ... What would be the best data model to represent this data model assuming that: - every Task property has a different type - list of activities will be stored in a database - list of activities will to be serialised to JSON format (and should be easily deserialised by the API client)
s

Stephan Schroeder

03/04/2023, 10:22 AM
But the tasks don't have access to the database (and they shouldn't) and are themselves probably stored in a Collection. I don't think you can store Delegates (in this case observable) in a Collection, can you?? 🤔 So maybe you have to implement the Observer pattern in the classic way yourself. Another thing: I'd make
Task
a data class and use less basic Types (Int, String), at least not in the domain class, the entity class (which is persisted in a database) on the other hand mustn't be a data class (since the automatically generated equals method doesn't have entity class semantics) and can use basic types. So how about
data class Task (
    val id: UUID,
    val name: String,
    val dueDate: Date,
    val priority: Priority,
    ...
)
with
Priority
either being an Enum
enum class Priority(val value: Int) {
    HIGH(1),
    MEDIUM(2),
    LOW(3)
}
or an inline class with additional validation that the int value is within valid bounds!?
@JvmInline
value class Priority(val value: Int) {
    init {
        require(value in 1..3) {"value $value out of range 1..3"}
    }
}