2020.03.11 Constructors for Database Entity classes in Kotlin - GlenKPeterson/One-off_Examples GitHub Wiki
Kotlin's null safety has me thinking very differently about constructing database entity classes:
- Any non-null fields should be initialized in object construction, either by being constructor parameters, or by being given sensible default values. Immutable objects require this, but mutable ones benefit from it because the constructor is then guaranteed to return a valid object.
- Unique keys in the database should correspond to required constructor parameters in your Kotlin classes. Even if this means that your primary constructor is private and you use an alternate constructor for convenience (say to split-up or combine classes to produce the desired unique fields).
- Unique keys are generally immutable (or should be).
- The surrogate key (numeric
IDfield) is generally not included in a unique constraint nor in the constructor. It is set to 0 until assigned by the database.
The result is that your constructor returns a valid object, even if you might want to tweak some less-important fields.
In Java, it would make sense to provide similar constructors, but null safety in Kotlin makes it obvious when you don't.
There is a loose relationship between unique keys and required constructor parameters such that required constructor parameters:
- Often uniquely identify an object and a subset can often be used in a unique constraint.
- Are usually necessary and sufficient for implementing
.equals()and.hashCode()
It's interesting to see these thoughts emerge as a result of converting Java code to Kotlin. Getting rid of those pesky "might return null" warnings actually has a silver lining in terms of application design.