1. Introduction
當你剛開始時,很容易被「做一個能涵蓋所有情況」的模型誘惑: name: String?, category: String?, amount: Int? — 之後再說。 此刻你等於是買到了自由……但那是分期付款,而且利率高得驚人。 因為接下來的每一段程式碼都會被迫用大量 null 檢查來「償還」: 輸出、排序、統計、格式化訊息,甚至最簡單的條件判斷都得處理。 Kotlin 當然會老實提醒你:nullable 型別需要明確處理。
How null “spreads” through the program
想像一下,在我們的主控台應用程式中(我們會延續一個實作範例——假想的支出追蹤器),你把支出資料存成這樣:
data class BadExpense(
val amountCents: Int?,
val category: String?,
val note: String?
)
一開始看起來:「很方便,甚至可以用很爛的輸入也建立物件」。但只要過兩三個函式就會變成:
- 「那 Int? 要怎麼加總?」
- 「如果 category == null 該怎麼辦?」
- 「note 可以直接列印嗎?」
- 「按 category 排序到底可不可以做?」
然後你的程式碼開始變成一片森林,充滿了 ?:、 ?.let {}、 if (x == null) return ...。
Key idea of the lecture
外面 nullable,裡面嚴格型別。
也就是說,null 可以出現在邊界(輸入、外部資料),但在正規化/驗證之後,我們必須得到沒有 nullable 欄位的內部物件。
2. Where null is acceptable—and where it is not
要設計成沒有 nullable 欄位,首先要先約定:null 到底在哪裡允許出現。 我們會用最務實的方式來做:不是「哲學上的對錯」,而是「讓程式碼不要生病」。
在真實應用中,null 的邊界幾乎總是在資料來自外部的地方: 使用者輸入字串、收到 HTTP 請求、讀取檔案、從資料庫取得資料。 今天我們不碰檔案/網路/DB,但原則相同: 外部輸入不可預測,內部模型——必須可預測。
這裡有個簡單流程圖,很值得放在腦中:
flowchart LR
A["Raw input (String? / String)"] --> B["Normalization (trim, lowercase, split)"]
B --> C["Parsing + validation (toIntOrNull, rules)"]
C --> D["Internal model (no null)"]
Table: “what is allowed and what is not”
| Program layer | Which types are acceptable there | What we consider normal |
|---|---|---|
| Input (CLI) | String, sometimes String? | Input may be empty/invalid |
| Normalization | String? for a short section | “Brought into shape”, but not confident yet |
| Parsing/validation | Result<T>, sealed result, sometimes T? | Errors should be explicit |
| Internal model (domain) | Only non-null (String, Int, enum, …) | If the object exists, it is valid |
3. Internal model: the object is always valid
現在我們要為主控台追蹤器設計一個嚴格的支出模型。 概念很簡單:如果清單裡放的是 Expense,那它就一定有金額、分類、備註 (或至少備註是空字串——但這必須是刻意做出的決策)。
我們會使用 data class,因為它是很方便的資料模型形式: Kotlin 會自動產生像 toString()、 equals()、copy() 和解構(destructuring)等實用方法。
Category as an enum, not a String
如果分類是字串,你很快就會得到 "Food"、"food"、"FOOD"、 "eda"、"Eda"、"EdA" 以及神秘的 "Foood"(這不是新分類,而是凌晨 3 點的人類打錯字)。
因此在嚴格模型中,我們把分類做成列舉:
enum class Category {
FOOD, TRANSPORT, FUN, OTHER
}
Strict Expense without nullable fields
來做支出模型。我們用「分」儲存金額(整數),因為用 Double 表示金錢——那是一種獨立的恐怖片類型。
data class Expense(
val id: Int,
val amountCents: Int,
val category: Category,
val note: String
) {
init {
require(id > 0) { "id must be positive" }
require(amountCents > 0) { "amountCents must be positive" }
require(note.isNotBlank()) { "note must not be blank" }
}
}
這裡我們把 require(...) 當作 fail-fast: 如果程式內部有人試圖建立一個「不正確的」 Expense, 最好立刻用清楚訊息崩潰,而不是把錯誤拖著跑。
重點:require 不是「驗證使用者輸入」 (因為對使用者輸入我們希望溫和地處理)。 它是在保護模型的不變式:也就是「這種物件不應該存在於程式內部」。
4. Raw input: a separate type with null
接著做今天的核心:為原始輸入建立獨立型別。 它可能很爛、為空、尚未解析、只有部分欄位。 這很正常,因為它還不是模型,只是一份素材。
一個很有用的小技巧(在真實專案也非常實用):不要嘗試立刻把輸入轉成 Expense。 改成先建立 Raw… 或 …Input, 然後用另一個函式把它轉成嚴格模型。
RawExpenseInput: data “as is”
data class RawExpenseInput(
val amount: String?,
val category: String?,
val note: String?
)
看起來太簡單?很好。 我們的目標不是「很聰明的類別」,而是誠實地裝下從外面進來的資料。
Normalization: bring strings into a reasonable form
正規化就是「把資料洗乾淨、梳理好」,但還不是「相信它」。 例如,如果字串只有空白,我們把它視為沒有值。
fun normalizeText(raw: String?): String? {
val s = raw?.trim()
return s?.takeIf { it.isNotEmpty() }
}
注意:normalizeText 回傳的是 String?。 這沒問題:它仍在邊界上工作。 但接下來我們會把這個 String? 轉成明確的結果型別。
5. Parsing: a sealed result instead of null
現在來到關鍵:要如何回傳解析/驗證結果,才能同時做到:
- 模型內部沒有 null,
- 呼叫端知道哪裡出了問題,
- 不在深處用一堆 println 把錯誤「吞掉」。
對教學專案而言,很適合做一個 sealed class 結果: 要嘛是 Ok,要嘛是 Error (也可以命名成 Invalid、Missing 等等)。
Parsing result: Ok/Error
sealed class ParseExpenseResult {
data class Ok(val draft: ExpenseDraft) : ParseExpenseResult()
data class Error(val message: String) : ParseExpenseResult()
}
那 ExpenseDraft 是什麼? 它是「內部有效(internally valid)的支出草稿」,但不含 id (id 通常是在加入清單/儲存庫時發放)。
data class ExpenseDraft(
val amountCents: Int,
val category: Category,
val note: String
)
ExpenseDraft 已經是嚴格型別:沒有 nullable 欄位。 這非常方便——後續邏輯只需要處理非 null 的資料。
Parsing the amount: from string to Int, in cents
為了簡化,我們用「分」作為輸入的整數,例如 199 = 199 cents。 (是的,這不是特別 user-friendly,但對學習很棒:我們避開了浮點數。)
fun parseAmountCents(text: String): Int? {
val x = text.toIntOrNull()
return x?.takeIf { it > 0 }
}
這裡回傳 Int? 是允許的, 因為這是一個邊界上的局部函式:「解析失敗」或「不符合規則」。
Parsing the category: from string to Category
fun parseCategory(text: String): Category? {
return when (text.trim().lowercase()) {
"food" -> Category.FOOD
"transport" -> Category.TRANSPORT
"fun" -> Category.FUN
"other" -> Category.OTHER
else -> null
}
}
這裡的 null 表示「無法辨識分類」。這是邊界上很正常的合約。
Build an ExpenseDraft from RawExpenseInput
現在把所有東西串起來。這就是那個「閘門」,它不讓 null 進到內部。
fun parseExpenseDraft(raw: RawExpenseInput): ParseExpenseResult {
val amountText = normalizeText(raw.amount)
?: return ParseExpenseResult.Error("Amount is missing")
val amount = parseAmountCents(amountText)
?: return ParseExpenseResult.Error("Amount must be a positive integer")
val categoryText = normalizeText(raw.category)
?: return ParseExpenseResult.Error("Category is missing")
val category = parseCategory(categoryText)
?: return ParseExpenseResult.Error("Unknown category: $categoryText")
val note = normalizeText(raw.note)
?: return ParseExpenseResult.Error("Note is missing")
return ParseExpenseResult.Ok(
ExpenseDraft(amountCents = amount, category = category, note = note)
)
}
注意這種風格:很多提早 return。 這讓程式碼很「扁平」:不會出現巨大巢狀的 if, 而且每個錯誤都會帶著具體原因回傳。 Kotlin 的做法「nullable 值 → 檢查 → 早退出」完全是正常實務。
6. CLI scenario: add an expense without null
接著把所有東西組成一個小情境。 我們有一個支出清單、一個 add 指令,使用者輸入資料。 我們刻意讓例子簡短,好讓你能在腦中一次看懂全貌。
Simple id generation
fun nextId(expenses: List<Expense>): Int {
val maxId = expenses.maxOfOrNull { it.id } ?: 0
return maxId + 1
}
maxOfOrNull 會回傳 nullable,因為清單可能是空的 — 這是典型的「集合邊界 nullable」。 我們用 Elvis ?: 把它乾淨地轉成 0, 接下來就又回到使用 Int,而不是 Int?。
Turn an ExpenseDraft into an Expense
在這裡,Expense 已經可以在 init 中套用自己的 require(...)。 但在正常流程裡其實不會走到違規:因為解析時就已經把所有規則都檢查完了。
fun createExpense(expenses: List<Expense>, draft: ExpenseDraft): Expense {
return Expense(
id = nextId(expenses),
amountCents = draft.amountCents,
category = draft.category,
note = draft.note
)
}
Parse the add command from a line
假設指令格式如下:
add <amountCents> <category> <note...>
例如:
add 199 food coffee
add 500 transport taxi to airport
我們做一個簡單的解析器(不包含之後會學到的主題,例如第 27 天的 Regex 驗證)。 讓 note 表示前兩個 token 之後的所有內容。
fun rawInputFromAddCommand(line: String): RawExpenseInput {
val parts = line.trim().split(" ")
val amount = parts.getOrNull(1)
val category = parts.getOrNull(2)
val note = parts.drop(3).joinToString(" ").takeIf { it.isNotBlank() }
return RawExpenseInput(amount = amount, category = category, note = note)
}
getOrNull 是一種非常誠實的表達:「元素可能不存在」。 同樣地:nullable 活在邊界上,而接下來我們會把它「壓實」成 ParseExpenseResult。
add command: full scenario
fun handleAdd(expenses: MutableList<Expense>, line: String) {
val raw = rawInputFromAddCommand(line)
when (val parsed = parseExpenseDraft(raw)) {
is ParseExpenseResult.Error -> println("ERROR: ${parsed.message}")
is ParseExpenseResult.Ok -> {
val expense = createExpense(expenses, parsed.draft)
expenses.add(expense)
println("Added: $expense") // Added: Expense(id=1, amountCents=199, category=FOOD, note=coffee)
}
}
}
注意:在 handleAdd 裡完全沒有 String?、 Int?, 更不用說 Expense?。 我們要嘛處理 Error(message),要嘛處理 Ok(draft)——這會大幅降低心智負擔。
Empty string instead of null: why sentinels are dangerous
有時候你會想:「那把 note: String? 改成 note: String, 如果使用者沒輸入就塞空字串不就好了?」 形式上確實移除了 nullable。 但問題是:空字串開始代表「沒有備註」,而且你必須到處記得這個規則。
哨兵值(sentinel values)(例如 ""、0、"UNKNOWN") 有時候可以接受,但前提是你願意把它固定成合約 並且只在一兩個地方處理,而不是把它塗抹到整個專案各處。
在我們的例子中,我們選了另一種合約: note 是必填而且不能是空的; 這會在邊界上檢查,並在模型內部用 require(note.isNotBlank()) 保護。
如果你真的需要「備註可選」,更好的做法不是用哨兵值,而是用另一種結果分支 或是在原始輸入層增加一個獨立欄位。 例如,RawExpenseInput.note 可以是 null, 但在組裝 ExpenseDraft 時,你可以做決策: 要嘛視為錯誤(像我們這樣),要嘛填入有意義的預設值。
7. Common mistakes
Mistake #1: making nullable fields in the domain model “just in case”.
這幾乎一定會導致 null 參與每一個操作: 統計、輸出、過濾、排序。 最後你寫的不是「支出記帳」,而是「記錄哪裡還可能出現 null」。 更划算的方式是承認:不可靠的是輸入資料,而不是內部模型: 引入 Raw…,驗證,然後才建立嚴格物件。
Mistake #2: returning Expense? from parsing and printing the error reason via println inside.
這會讓呼叫端只得到「有物件或沒有物件」,但不知道為什麼沒有。 而錯誤原因在深處直接輸出到主控台,和其他訊息混在一起。 用 sealed class 結果(Ok/Error)或 Result<T> 會更乾淨: 原因成為值的一部分,而不是副作用。
Mistake #3: mixing “input error” and “internal failure” under the same handling style.
使用者把 "abc" 當成數字輸入——這是預期內的情況, 應該回傳 Error("Amount must be...")。 但如果你用已經驗證過的資料,卻還試圖建立 Expense(amountCents = -10), 那更像是程式 bug,此時在模型裡用 require(...)(fail-fast)才合理。
Mistake #4: saying “we already checked it”, but still using !!.
!! 通常出現的原因是:你沒有明確約定 null 的邊界到底在哪裡。 在我們的方法裡,邊界在 parsing:當我們還在 Raw… 和 normalization 時,nullable 是允許的; 但一旦拿到 ParseExpenseResult.Ok,內部就不該再有任何使用 !! 的理由。 如果你手會伸向 !!,那是個很好的訊號:要嘛漏了驗證,要嘛把層次混在一起了。
Mistake #5: having nullable fields in the Ok branch of a sealed result (“Ok, but the value can be null”).
這是一種把 null「戴面具」帶回來的狡猾方式。 最後你會得到 Ok(value: T?), 不確定性又被你帶回內部。 如果結果是 Ok,它就應該包含沒有 null 的嚴格值, 否則嚴格模型的核心想法就會崩壞。
GO TO FULL VERSION