Designing Objects in Kotlin
In this pack: sizing and rule strictness are set by the core
plugin's oo-design skill; each rule here keeps a core rule in this
language.
Overview
Kotlin puts much of a design into the type system: a data class for a
value, a @JvmInline value class for one property that carries a
rule, a sealed interface for a set the clinic closes, and a nullable
type for an answer that may be absent. This skill applies the pack's
core rules to plain Kotlin, from Kotlin 2.0 on, on the JVM, with no
framework. It says which feature keeps each rule and how the compiler
then helps: an init block that a copy() cannot skip, a when that a
new case cannot leave half-answered, and a value that cannot be read as
present unless the compiler has seen the check.
When to use
- A data class holds several fields, and two instances with the same
contents stand for the same thing.
- A data class's checks sit in a factory or a secondary constructor, and
a caller can reach the primary constructor.
- A set of cases is closed, and code answers it with a
when that has
an else branch.
- A property or a return type may be absent, and the code asserts a
value with
!!.
- Several implementations of one interface share behaviour, or a class
extends an
open class only to reuse its code.
- A helper function on a class's type starts to hold a rule that
belongs to the class.
When not to use
- The classes are built or wired by a framework, such as one for a
phone's screens or for a server: outside this skill.
- The question is one no Kotlin feature changes, such as which object
owns a rule or where a module's boundary runs: the core skills,
starting from
oo-design.
- The code shares one source between several platforms: outside this
skill.
Core rules
Rule. Check a data class's rules in an init block with require,
never only in a factory or a secondary constructor. Every copy()
reaches the primary constructor, so the init block checks each
copy, while a check kept in a factory runs for no copy at all;
require throws an IllegalArgumentException that names the rule
the value broke, as oo-constructing-valid-objects rules 1 and 3
ask.
Default. Write a value as a data class whose properties are all
val and all declared in the primary constructor, so its equals,
hashCode and copy are derived from all of its contents, as
oo-modeling-values-and-entities rules 2 and 3 ask; a property
declared in the class body is left out of them. The exception is a
value that holds a single property, such as a patient's identifier:
write it as a @JvmInline value class, a type of its own around
that one property, as oo-modeling-values-and-entities rule 5 asks.
Default. Close a set of cases the domain closes with a sealed interface whose cases are data classes and data objects, and answer
each case in a when expression that names every case and has no
else branch, as oo-making-illegal-states-impossible rule 2 and
oo-patterns-the-language-provides rule 5 ask: the compiler checks
that every case is covered. The exception is a set that gains new
kinds more often than new operations: give each kind its behaviour as
a member of the interface, as
oo-replacing-conditionals-with-polymorphism rule 7 weighs it.
Rule. Declare a property or a return type nullable only where the
domain lets the value be absent, and never assert a value present
with !! on a path the clinic's rules run. A value that every
state carries is not nullable, as
oo-making-illegal-states-impossible rule 6 asks. Handle an absent
value where it is read, with ?., ?: or a check the compiler
sees, as oo-designing-failure-behaviour rule 5 asks; where absence
is an error, ?: throw raises the refusal it is.
Default. Reuse an interface's behaviour by class delegation, with
by, rather than by extending a class, as
oo-choosing-composition-over-inheritance rule 1 asks: the compiler
writes the forwarding methods, and the class overrides only what it
changes. A method the delegate runs itself never reaches the
delegating class's overrides, and the class gives by only an
interface whose every message it means to offer, as
oo-choosing-composition-over-inheritance rule 6 asks. The exception
is a sealed hierarchy: its subtypes are the hierarchy's cases, not
reuses of a parent's code (rule 3).
Judgement. Write an extension function only for what needs the
receiver's public members alone and holds none of the receiver's
rules, such as formatting a visit for one screen. A class's rule
belongs in the class, where oo-encapsulating-state-and-behaviour
rule 1 keeps an invariant with the state it guards and
oo-assigning-responsibilities rule 1 gives a behaviour to the
object that holds its information. The compiler resolves an
extension statically, from the declared type, so a subtype's function
cannot override it, and the extension cannot read the receiver's
private members. What tips the balance is whose words the function
speaks: the receiver's own words make it a member, while one
caller's words keep it an extension beside that caller.
Pattern
ExercisePlan is the exercise a physiotherapist sets a patient to
repeat at home between visits, with its repetitions and its sets a day.
Two plans with the same contents are the same plan, which makes it a
value (oo-modeling-values-and-entities rule 1).
Before:
data class ExercisePlan(
val exercise: String,
val repetitions: Int,
val setsPerDay: Int,
) {
companion object {
fun of(
exercise: String,
repetitions: Int,
setsPerDay: Int,
): ExercisePlan {
require(exercise.isNotBlank()) { "the plan names its exercise" }
require(repetitions > 0) { "at least one repetition" }
require(setsPerDay > 0) { "at least one set a day" }
return ExercisePlan(exercise, repetitions, setsPerDay)
}
}
}
In the Before, the checks sit in the factory of, so the public
primary constructor and every copy() build a plan the clinic forbids;
copy(setsPerDay = 0) is one such plan (rule 1).
After:
data class ExercisePlan(
val exercise: String,
val repetitions: Int,
val setsPerDay: Int,
) {
init {
require(exercise.isNotBlank()) { "the plan names its exercise" }
require(repetitions > 0) { "at least one repetition" }
require(setsPerDay > 0) { "at least one set a day" }
}
}
In the After, the init block runs for every construction, copy()
included, so no such plan can exist (rule 1), and all three properties
are vals in the primary constructor, so equals, hashCode and
copy read all of them (rule 2). require throws an
IllegalArgumentException with the message its block gives, and
isNotBlank answers whether a string holds a character other than
white space. The fences store nothing. The init block reads only
properties the primary constructor set.
Red flags
Places to look, not verdicts. A red flag becomes a finding only with
evidence: a measurement, a reproducible bug, or a failing test.
- A
!! on a property the domain always has, such as an appointment's
clinician.
- A data class whose checks sit only in a factory or a secondary
constructor, with none in
init.
- A
var property in a data class.
- A
when over a sealed type with an else branch.
- An extension function that holds a rule of the receiver.
- A class that extends an
open class only to reuse its code.
Common mistakes
- Making a property nullable because a later step fills it in.
- Putting a data class's checks in a factory, so
copy() skips them.
- Declaring part of a value's contents in the class body, where
equals does not read it.
- Adding an
else branch to a when to quiet the compiler.
- Turning helpers into extension functions until a class's rules are
spread over several files.
- Marking classes
open by habit.
Related skills
oo-design sizes a task and defines the rule labels.
oo-constructing-valid-objects makes a constructor refuse broken
input.
oo-modeling-values-and-entities decides whether a concept is a
value or an entity, and what equality reads.
oo-making-illegal-states-impossible closes a set of states where
the domain closes it.
oo-designing-failure-behaviour tells a refusal from a fault and
chooses how absence is answered.
oo-choosing-composition-over-inheritance decides when to hold an
object instead of extending a class.
oo-encapsulating-state-and-behaviour keeps an invariant with the
state it guards.
oo-assigning-responsibilities gives a behaviour to the object that
holds its information.
oo-patterns-the-language-provides shows when a language feature
replaces a pattern.
Further reading
1---2name: oo-kotlin3description: Use when plain Kotlin code with no framework needs a data class or a sealed type, a choice of nullable types, delegation with by, or extension functions.4license: MIT5metadata:6 source: https://skillmd.com/skills/yutna/oo-kotlin7 version: 0.21.08 pack: object-oriented-design-skills9---1011# Designing Objects in Kotlin1213**In this pack:** sizing and rule strictness are set by the core14plugin's `oo-design` skill; each rule here keeps a core rule in this15language.1617## Overview1819Kotlin puts much of a design into the type system: a `data class` for a20value, a `@JvmInline` `value class` for one property that carries a21rule, a `sealed interface` for a set the clinic closes, and a nullable22type for an answer that may be absent. This skill applies the pack's23core rules to plain Kotlin, from Kotlin 2.0 on, on the JVM, with no24framework. It says which feature keeps each rule and how the compiler25then helps: an `init` block that a `copy()` cannot skip, a `when` that a26new case cannot leave half-answered, and a value that cannot be read as27present unless the compiler has seen the check.2829## When to use3031- A data class holds several fields, and two instances with the same32 contents stand for the same thing.33- A data class's checks sit in a factory or a secondary constructor, and34 a caller can reach the primary constructor.35- A set of cases is closed, and code answers it with a `when` that has36 an `else` branch.37- A property or a return type may be absent, and the code asserts a38 value with `!!`.39- Several implementations of one interface share behaviour, or a class40 extends an `open` class only to reuse its code.41- A helper function on a class's type starts to hold a rule that42 belongs to the class.4344## When not to use4546- The classes are built or wired by a framework, such as one for a47 phone's screens or for a server: outside this skill.48- The question is one no Kotlin feature changes, such as which object49 owns a rule or where a module's boundary runs: the core skills,50 starting from `oo-design`.51- The code shares one source between several platforms: outside this52 skill.5354## Core rules55561. Rule. **Check a data class's rules in an `init` block with `require`,57 never only in a factory or a secondary constructor.** Every `copy()`58 reaches the primary constructor, so the `init` block checks each59 copy, while a check kept in a factory runs for no copy at all;60 `require` throws an `IllegalArgumentException` that names the rule61 the value broke, as `oo-constructing-valid-objects` rules 1 and 362 ask.63642. Default. **Write a value as a `data class` whose properties are all65 `val` and all declared in the primary constructor, so its `equals`,66 `hashCode` and `copy` are derived from all of its contents, as67 `oo-modeling-values-and-entities` rules 2 and 3 ask; a property68 declared in the class body is left out of them.** The exception is a69 value that holds a single property, such as a patient's identifier:70 write it as a `@JvmInline` `value class`, a type of its own around71 that one property, as `oo-modeling-values-and-entities` rule 5 asks.72733. Default. **Close a set of cases the domain closes with a `sealed74 interface` whose cases are data classes and data objects, and answer75 each case in a `when` expression that names every case and has no76 `else` branch, as `oo-making-illegal-states-impossible` rule 2 and77 `oo-patterns-the-language-provides` rule 5 ask: the compiler checks78 that every case is covered.** The exception is a set that gains new79 kinds more often than new operations: give each kind its behaviour as80 a member of the interface, as81 `oo-replacing-conditionals-with-polymorphism` rule 7 weighs it.82834. Rule. **Declare a property or a return type nullable only where the84 domain lets the value be absent, and never assert a value present85 with `!!` on a path the clinic's rules run.** A value that every86 state carries is not nullable, as87 `oo-making-illegal-states-impossible` rule 6 asks. Handle an absent88 value where it is read, with `?.`, `?:` or a check the compiler89 sees, as `oo-designing-failure-behaviour` rule 5 asks; where absence90 is an error, `?: throw` raises the refusal it is.91925. Default. **Reuse an interface's behaviour by class delegation, with93 `by`, rather than by extending a class, as94 `oo-choosing-composition-over-inheritance` rule 1 asks: the compiler95 writes the forwarding methods, and the class overrides only what it96 changes.** A method the delegate runs itself never reaches the97 delegating class's overrides, and the class gives `by` only an98 interface whose every message it means to offer, as99 `oo-choosing-composition-over-inheritance` rule 6 asks. The exception100 is a sealed hierarchy: its subtypes are the hierarchy's cases, not101 reuses of a parent's code (rule 3).1021036. Judgement. **Write an extension function only for what needs the104 receiver's public members alone and holds none of the receiver's105 rules, such as formatting a visit for one screen.** A class's rule106 belongs in the class, where `oo-encapsulating-state-and-behaviour`107 rule 1 keeps an invariant with the state it guards and108 `oo-assigning-responsibilities` rule 1 gives a behaviour to the109 object that holds its information. The compiler resolves an110 extension statically, from the declared type, so a subtype's function111 cannot override it, and the extension cannot read the receiver's112 private members. What tips the balance is whose words the function113 speaks: the receiver's own words make it a member, while one114 caller's words keep it an extension beside that caller.115116## Pattern117118`ExercisePlan` is the exercise a physiotherapist sets a patient to119repeat at home between visits, with its repetitions and its sets a day.120Two plans with the same contents are the same plan, which makes it a121value (`oo-modeling-values-and-entities` rule 1).122123Before:124125```kotlin126data class ExercisePlan(127 val exercise: String,128 val repetitions: Int,129 val setsPerDay: Int,130) {131 companion object {132 fun of(133 exercise: String,134 repetitions: Int,135 setsPerDay: Int,136 ): ExercisePlan {137 require(exercise.isNotBlank()) { "the plan names its exercise" }138 require(repetitions > 0) { "at least one repetition" }139 require(setsPerDay > 0) { "at least one set a day" }140 return ExercisePlan(exercise, repetitions, setsPerDay)141 }142 }143}144```145146In the Before, the checks sit in the factory `of`, so the public147primary constructor and every `copy()` build a plan the clinic forbids;148`copy(setsPerDay = 0)` is one such plan (rule 1).149150After:151152```kotlin153data class ExercisePlan(154 val exercise: String,155 val repetitions: Int,156 val setsPerDay: Int,157) {158 init {159 require(exercise.isNotBlank()) { "the plan names its exercise" }160 require(repetitions > 0) { "at least one repetition" }161 require(setsPerDay > 0) { "at least one set a day" }162 }163}164```165166In the After, the `init` block runs for every construction, `copy()`167included, so no such plan can exist (rule 1), and all three properties168are `val`s in the primary constructor, so `equals`, `hashCode` and169`copy` read all of them (rule 2). `require` throws an170`IllegalArgumentException` with the message its block gives, and171`isNotBlank` answers whether a string holds a character other than172white space. The fences store nothing. The `init` block reads only173properties the primary constructor set.174175## Red flags176177Places to look, not verdicts. A red flag becomes a finding only with178evidence: a measurement, a reproducible bug, or a failing test.179180- A `!!` on a property the domain always has, such as an appointment's181 clinician.182- A data class whose checks sit only in a factory or a secondary183 constructor, with none in `init`.184- A `var` property in a data class.185- A `when` over a sealed type with an `else` branch.186- An extension function that holds a rule of the receiver.187- A class that extends an `open` class only to reuse its code.188189## Common mistakes190191- Making a property nullable because a later step fills it in.192- Putting a data class's checks in a factory, so `copy()` skips them.193- Declaring part of a value's contents in the class body, where194 `equals` does not read it.195- Adding an `else` branch to a `when` to quiet the compiler.196- Turning helpers into extension functions until a class's rules are197 spread over several files.198- Marking classes `open` by habit.199200## Related skills201202- `oo-design` sizes a task and defines the rule labels.203- `oo-constructing-valid-objects` makes a constructor refuse broken204 input.205- `oo-modeling-values-and-entities` decides whether a concept is a206 value or an entity, and what equality reads.207- `oo-making-illegal-states-impossible` closes a set of states where208 the domain closes it.209- `oo-designing-failure-behaviour` tells a refusal from a fault and210 chooses how absence is answered.211- `oo-choosing-composition-over-inheritance` decides when to hold an212 object instead of extending a class.213- `oo-encapsulating-state-and-behaviour` keeps an invariant with the214 state it guards.215- `oo-assigning-responsibilities` gives a behaviour to the object that216 holds its information.217- `oo-patterns-the-language-provides` shows when a language feature218 replaces a pattern.219220## Further reading221222- [Cases and absence](references/cases-and-absence.md)