Thuta Learning
Kotlin
AdvancedProgrammingအခြေခံ

Sealed Types, Exceptions & Result

Kotlinသင်ခန်းစာ 2240 မိနစ်

ဒီခန်းပြီးရင် ဘာတတ်သွားမလဲ

  • Failure တစ်ခုအတွက် exception၊ Result နဲ့ sealed type ထဲက သင့်တာကို ရွေးနိုင်ဖို့
  • require၊ check နဲ့ error ကို သုံးပြီး တစ်ခုစီက ဘယ် exception ကို throw လုပ်လဲ ပြောနိုင်ဖို့
  • runCatching နဲ့ အန္တရာယ်ရှိတဲ့ code ကို ထုပ်ပြီး getOrElse၊ getOrNull နဲ့ fold နဲ့ ဖတ်နိုင်ဖို့
  • sealed interface နဲ့ else မပါတဲ့ exhaustive when ကို ရေးပြီး else မထည့်တာက ဘာကြောင့် အဓိကလဲ ရှင်းပြနိုင်ဖို့
  • ဒေတာတစ်ခု သယ်တဲ့ custom exception တစ်ခုကို သတ်မှတ်နိုင်ဖို့

ရိုးရိုးလေး ရှင်းပြမယ်

Failure ကို ရိုးရိုးလေး ပြောရရင်

အရာတွေ မှားတတ်ပါတယ်: user က နံပါတ်ရေးရမယ့်နေရာမှာ 'abc' ရိုက်တယ်၊ network call က time out ဖြစ်တယ်၊ လက်ကျန်ငွေ မလောက်ဘူး။ Kotlin မှာ ကိုင်တွယ်နည်း သုံးမျိုး ရှိပါတယ်။ Exception က program ကို ရပ်ပြီး အနီးဆုံး catch ဆီ ခုန်သွားပါတယ်။ Result ကတော့ အဖြေ ဒါမှမဟုတ် error တစ်ခုခုကို ကိုင်ထားတဲ့ value ဖြစ်လို့ ခေါ်သူက ကြည့်ရမှာပါ။ Sealed type ကတော့ Paid၊ Declined၊ Offline လို ကိုယ်တိုင်ဒီဇိုင်းလုပ်တဲ့ ဖြစ်နိုင်ခြေ အဆုံးသတ်စာရင်းတစ်ခုပါ။

ကောင်တာမှာ မှာတာကို စဉ်းစားကြည့်ပါ။ Exception က 'မီးလောင်ပြီ!' လို့ အော်လိုက်တာနဲ့ တူပါတယ်: တာဝန်ရှိသူ တစ်ယောက်က ဖြေရှင်းတဲ့အထိ အရာအားလုံး ရပ်ပါတယ်။ Result က သင့်မှာထားတာ ဒါမှမဟုတ် တောင်းပန်စာတစ်ခုခုကို ထည့်ထားတဲ့ ပိတ်ထားတဲ့ စာအိတ်လို ဖြစ်ပြီး သင်က ဖွင့်ကြည့်ရပါမယ်။ Sealed type ကတော့ ရလဒ်အစုံ ပုံနှိပ်ထားတဲ့ menu လိုပါပဲ၊ ဒါကြောင့် ဝန်ထမ်းတွေက လူတိုင်းဖတ်တဲ့ menu ကို မပြင်ဘဲ ရလဒ်အသစ်ကို မဖန်တီးနိုင်ပါဘူး။

Problem → Why → Solution

ပြဿနာ: crash၊ တိတ်ဆိတ်တဲ့ 0 နဲ့ Boolean က မပြောပြနိုင်တာ

Function တစ်ခုက user input ကနေ port number ကို parse လုပ်ပါတယ်။ ပထမ version က toInt() ကိုပဲ ခေါ်တာမို့ 'http' ဆိုရင် NumberFormatException နဲ့ program crash ဖြစ်ပြီး signature ထဲမှာ ခေါ်သူကို သတိပေးတာ ဘာမှ မရှိပါဘူး။ ဒုတိယ version က အားလုံးကို catch လုပ်ပြီး 0 ပြန်တာမို့ typo တစ်ခုက တိတ်တိတ်လေး port 0 ဖြစ်သွားပြီး အကြောင်းအရင်း အစစ်ပျောက်သွားပါတယ်။ နောက်ပိုင်း code base တစ်ခုတည်းမှာ နေရာတစ်ခုက null၊ တစ်ခုက -1၊ တစ်ခုက throw ပြန်လာပြီး ခေါ်သူတိုင်းက ဘယ် convention ကို သုံးရမလဲ မှတ်ထားရပါတယ်။

ဖြစ်နိုင်ခြေနှစ်ခုထက်ပိုတဲ့ ရလဒ်တွေက ပိုဆိုးပါတယ်။ ငွေပေးချေမှုတစ်ခုက အောင်မြင်နိုင်တယ်၊ ငြင်းပယ်ခံရနိုင်တယ်၊ network ပျက်လို့ မအောင်မြင်နိုင်တယ်။ ဒါတွေကို Boolean တစ်ခုထဲ ညှစ်ထည့်လိုက်ရင် ခေါ်သူက ငြင်းပယ်ခံရတဲ့ ကတ်နဲ့ ပျက်နေတဲ့ network ကို မခွဲနိုင်တော့ပါဘူး။

failure-by-accident.kt
fun portCrash(text: String): Int = text.toInt() // "http" throws NumberFormatException

fun portSilent(text: String): Int =
    try { text.toInt() } catch (e: Exception) { 0 }

fun pay(balance: Int, price: Int): Boolean = price <= balance

fun main() {
    println(portSilent("http")) // 0: the reason is gone
    println(pay(100, 250))      // false: declined, offline or broken? nobody knows
}

Failure ကို type ထဲမှာ နေရာပေးရတယ်

Failure က function ရဲ့ စာချုပ်ရဲ့ အစိတ်အပိုင်းဖြစ်လို့ type တွေထဲမှာ နေရာရထိုက်ပါတယ်။ Result က 'ဒါက fail ဖြစ်နိုင်တယ်' ဆိုတာကို signature ထဲမှာ မြင်ရစေပြီး sealed type က ရလဒ်တိုင်းကို နာမည်နဲ့ စာရင်းပေးထားလို့ compiler က ခေါ်သူတိုင်းကို ကိစ္စတစ်ခုစီ ကိုင်ဖို့ တွန်းအားပေးနိုင်ပါတယ်။ Exception ကတော့ bug တွေအတွက်နဲ့ stack အပေါ်ပိုင်းက ဘယ်သူမှ ဆီလျော်စွာ ပြင်လို့မရတဲ့ အခြေအနေတွေအတွက် မှန်ကန်တဲ့ tool အဖြစ် ဆက်ရှိနေပါတယ်။

Core concept: exception၊ Result နဲ့ sealed type

Exception ကို throw နဲ့ ပစ်ပြီး try/catch နဲ့ ဖမ်းပါတယ်။ try က expression ပါ: val n = try { text.toInt() } catch (e: NumberFormatException) { -1 }။ Kotlin မှာ checked exception မရှိတဲ့အတွက် ခေါ်သူကို catch ဖို့ ဘာမှ မတွန်းအားပေးပါဘူး၊ ဒါကြောင့် function signature က သူ့ failure တွေကို စာရင်းပေးတယ်လို့ မယုံနိုင်ပါဘူး။ ကိုယ်ပိုင် exception ကို Exception ကို extend လုပ်ပြီး ဆောက်ပါတယ်: class InsufficientFundsException(val shortBy: Int) : Exception("...")၊ ထပ်ထည့်ထားတဲ့ field တွေက catch သူကို message ကို parse မလုပ်ဘဲ တုံ့ပြန်ခွင့်ပေးပါတယ်။

Standard function သုံးခုက ကျိုးသွားတဲ့ ယူဆချက်ကို message ရှင်းရှင်းနဲ့ exception အဖြစ် ပြောင်းပေးပါတယ်။ require(condition) { message } က argument ကို စစ်ပြီး IllegalArgumentException ကို throw လုပ်ပါတယ်။ check(condition) { message } က state ကို စစ်ပြီး IllegalStateException ကို throw လုပ်ပါတယ်။ error(message) က IllegalStateException ကို ချက်ချင်း throw လုပ်ပြီး return type က Nothing ဖြစ်လို့ ?: error(...) လို expression ထဲမှာ အဆင်ပြေပါတယ်။ requireNotNull နဲ့ checkNotNull ကလည်း null အတွက် အတူတူလုပ်ပြီး ပြီးရင် value ကို smart cast လုပ်ပေးပါတယ်။

FunctionThrow တာသုံးရမယ့်နေရာ
requireIllegalArgumentExceptionခေါ်သူက မှားတဲ့ argument ပေးတဲ့အခါ
checkIllegalStateExceptionobject က မှားတဲ့ state ထဲ ရောက်နေတဲ့အခါ
errorIllegalStateExceptionမဖြစ်သင့်တဲ့ branch ဒါမှမဟုတ် မတွေ့တဲ့ item

Result<T> ဆိုတာ အောင်မြင်မှု ဒါမှမဟုတ် မအောင်မြင်မှုတစ်ခုကို ကိုင်ထားတဲ့ value ပါ။ runCatching { ... } က block ကို run ပြီး ထွက်လာတဲ့ Throwable ဘာမဆိုကို Result ထဲ ဖမ်းပေးပါတယ်။ ပြီးတော့ ဖတ်ပါတယ်: getOrNull က value ဒါမှမဟုတ် null ပြန်ပေး၊ getOrElse { default } က error ကနေ fallback တွက်ပေး၊ getOrThrow က ပြန် throw လုပ်ပေး၊ fold(onSuccess, onFailure) က နှစ်ဖက်လုံးကို ကိုင်ပေးပါတယ်။ map က အောင်မြင်မှုကို ပြောင်းပြီး မအောင်မြင်မှုကို မထိပါဘူး။ Function တစ်ခုက Result<Int> ကို return type အဖြစ် ကြေညာနိုင်လို့ ခေါ်သူက signature မှာတင် fail ဖြစ်နိုင်ကြောင်း မြင်ရပါတယ်။ User input ကို parse တာလို မျှော်လင့်ထားတဲ့၊ နီးကပ်တဲ့ failure တွေမှာ သုံးပါ။

Sealed interface (ဒါမှမဟုတ် sealed class) က subtype တွေရဲ့ ပိတ်ထားတဲ့ အစုတစ်ခုကို ကြေညာပါတယ်၊ subtype အားလုံးကို compiler က သိပါတယ် ဘာကြောင့်လဲဆိုတော့ package နဲ့ module တစ်ခုတည်းထဲမှာ ရှိရလို့ပါ။ Sealed value ပေါ်က when ကို expression အဖြစ် သုံးရင် else မလိုပါဘူး: compiler က subtype တိုင်းကို ဖုံးကြောင်း စစ်ပေးပြီး နောက်မှ subtype အသစ်ထည့်ရင် အဲဒီလို when တိုင်းက handle မလုပ်မချင်း compile မဖြစ်တော့ပါဘူး။ ဒေတာသယ်တဲ့ ရလဒ်တွေအတွက် data class၊ မသယ်တာတွေအတွက် data object ကို သုံးပါ။ Smart cast ကြောင့် is Payment.Paid branch ထဲမှာ payment.receipt ကို တိုက်ရိုက်သုံးလို့ ရပါတယ်။

ဘာမှားလဲ ပြောရတဲ့ နည်းသုံးမျိုး
  1. Bug ဒါမှမဟုတ် input မှား: exception
  2. မျှော်လင့်ထားတဲ့ failure: Result ပြန်
  3. ရလဒ်များများ: sealed type သုံး
  4. when က ကိစ္စအားလုံးကို ဖုံး၊ else မလို

ဘယ်သူ ပြင်နိုင်လဲ မေးပါ: အနီးမှာ ဘယ်သူမှ မပြင်နိုင်ရင် exception၊ တိုက်ရိုက်ခေါ်သူက ပြင်နိုင်ရင် Result ဒါမှမဟုတ် sealed type ပါ။

အထွေထွေ ပုံစံ

kotlin
require(condition) { "message" }    // IllegalArgumentException
check(condition) { "message" }      // IllegalStateException

val result: Result<T> = runCatching { riskyCode() }
result.getOrElse { error -> fallback }

sealed interface Outcome {
    data class Success(val value: T) : Outcome
    data object Failure : Outcome
}
when (outcome) { is Outcome.Success -> ...; Outcome.Failure -> ... }

require နဲ့ check က အဖြေ မမှန်တဲ့အခါ exception ပစ်ပါတယ်၊ runCatching က exception ကို value အဖြစ် ပြောင်းပါတယ်၊ sealed interface က ဖြစ်နိုင်တဲ့ ရလဒ်တွေကို စာရင်းပိတ်ပေးပြီး when က အဲဒီရလဒ်တိုင်းကို ကိုင်ရပါတယ်။

Worked example: port parse လုပ်ခြင်းနဲ့ ငွေပေးချေခြင်း

Program မှာ ကိစ္စနှစ်ခု ပါပါတယ်။ parsePort က မမှန်တဲ့ input ကို Result အဖြစ် ပြန်ပေးပြီး pay က Payment ဆိုတဲ့ sealed interface ရဲ့ subtype တစ်ခုကို ပြန်ပေးပါတယ်။ describe ထဲက when မှာ else မရှိတာကို သတိထားပါ၊ compiler က ကိစ္စအားလုံး ဖုံးမဖုံး စစ်ပေးနေတာပါ။

payment.kt
sealed interface Payment {
    data class Paid(val receipt: String) : Payment
    data class Declined(val reason: String) : Payment
    data object Offline : Payment
}

fun parsePort(text: String): Result<Int> = runCatching {
    val port = text.trim().toInt()
    require(port in 1..65535) { "port $port is outside 1..65535" }
    port
}

fun pay(balance: Int, price: Int, online: Boolean): Payment = when {
    !online -> Payment.Offline
    price <= 0 -> Payment.Declined("price must be positive")
    price > balance -> Payment.Declined("short by ${price - balance}")
    else -> Payment.Paid("R-$price")
}

fun describe(payment: Payment): String = when (payment) {
    is Payment.Paid -> "paid, receipt ${payment.receipt}"
    is Payment.Declined -> "declined: ${payment.reason}"
    Payment.Offline -> "offline, try again later"
}

fun main() {
    for (text in listOf("8080", "http", "70000")) {
        val message = parsePort(text).fold(
            onSuccess = { port -> "port $port ok" },
            onFailure = { error -> "bad input '$text': ${error.message}" },
        )
        println(message)
    }
    println(parsePort("443").getOrElse { 80 })
    println(parsePort("abc").getOrElse { 80 })

    println(describe(pay(balance = 100, price = 40, online = true)))
    println(describe(pay(balance = 100, price = 250, online = true)))
    println(describe(pay(balance = 100, price = 40, online = false)))
}

Code ကို တစ်ပိုင်းချင်း ရှင်းပြမယ်

  1. A closed set of outcomessealed interface Payment {

    Sealed interface က Payment ရဲ့ subtype တွေကို Paid၊ Declined နဲ့ Offline သုံးမျိုးတည်းလို့ ပိတ်ပေးပါတယ်။ တခြား file ကနေ တတိယ subtype ကို မထည့်နိုင်တဲ့အတွက် compiler က ဖြစ်နိုင်တာ အားလုံးကို သိပါတယ်။

  2. An outcome without datadata object Offline : Payment

    Offline မှာ သယ်စရာ ဒေတာ မရှိတဲ့အတွက် data class မဟုတ်ဘဲ data object ဖြစ်ပါတယ်၊ တစ်ခုတည်းသော instance ရှိပြီး print ထုတ်ရင် နာမည် ကောင်းကောင်းပေါ်ပါတယ်။ Paid နဲ့ Declined ကတော့ receipt နဲ့ reason ကို data class နဲ့ သယ်ပါတယ်။

  3. Result from runCatchingfun parsePort(text: String): Result<Int> = runCatching {

    Return type Result<Int> ကြောင့် ခေါ်သူက fail ဖြစ်နိုင်ကြောင်း signature မှာတင် မြင်ရပါတယ်။ runCatching ရဲ့ block ထဲက exception တစ်ခုခု ထွက်လာရင် ပစ်မလွှတ်ဘဲ Result ထဲ ဖမ်းထားပြီး block ရဲ့ နောက်ဆုံး expression port က အောင်မြင်ရင် ရလဒ်ဖြစ်ပါတယ်။

  4. A precondition with a messagerequire(port in 1..65535) { "port $port is outside 1..65535" }

    require က အကွာအဝေးကို စစ်ပြီး မကျော်ရင် IllegalArgumentException ကို ပစ်ပါတယ်။ { ... } ထဲက message ကို condition မှားမှသာ တည်ဆောက်တာမို့ အလကား cost မရှိပါဘူး။ runCatching ကနေ error.message အဖြစ် ပြန်ထွက်လာတာမို့ 70000 အတွက် port 70000 is outside 1..65535 လို့ ပြပါတယ်။

  5. Exhaustive whenfun describe(payment: Payment): String = when (payment) {

    when ကို expression အဖြစ် သုံးထားပြီး Paid၊ Declined နဲ့ Offline သုံးခုလုံးကို ရေးထားတာမို့ else မလိုပါဘူး။ is Payment.Paid branch ထဲမှာ payment ကို Paid အဖြစ် smart cast လုပ်ပေးလို့ payment.receipt ကို တိုက်ရိုက်သုံးလို့ရပါတယ်။ Subtype အသစ်ထည့်ရင် ဒီ function က compile မဖြစ်တော့ပါဘူး။

  6. Reading a Resultprintln(parsePort("abc").getOrElse { 80 })

    fold က success နဲ့ failure နှစ်ဖက်လုံးအတွက် message ကို တည်ဆောက်ပါတယ်။ getOrElse ကတော့ fail ဖြစ်ရင် fallback ကို တွက်ပေးတာမို့ parsePort("abc") က exception မပစ်ဘဲ 80 ကို ပြန်ပေးပါတယ်၊ parsePort("443") ကတော့ 443 ပါ။

You should see
port 8080 ok
bad input 'http': For input string: "http"
bad input '70000': port 70000 is outside 1..65535
443
80
paid, receipt R-40
declined: short by 150
offline, try again later

Custom exception နဲ့ try/catch/finally

ကိုယ်ပိုင် exception ရဲ့ တန်ဖိုးက ဒေတာသယ်နိုင်တာပါ: InsufficientFundsException က shortBy ကို သယ်လို့ catch သူက message ကို parse မလုပ်ဘဲ တုံ့ပြန်နိုင်ပါတယ်။ catch block တွေက အပေါ်ကနေ အောက် ကိုက်ညီတဲ့ပထမတစ်ခုကို ရွေးတာမို့ အတိအကျ exception ကို အရင်ရေးပါ၊ finally ကတော့ အောင်မြင်သည်ဖြစ်စေ၊ catch သည်ဖြစ်စေ အမြဲ run ပါတယ်။

custom-exception.kt
class InsufficientFundsException(val shortBy: Int) :
    Exception("Not enough balance, short by $shortBy")

fun withdraw(balance: Int, amount: Int): Int {
    require(amount > 0) { "amount must be positive, got $amount" }
    if (amount > balance) throw InsufficientFundsException(amount - balance)
    return balance - amount
}

fun main() {
    for (amount in listOf(30, -5, 500)) {
        try {
            println("new balance: ${withdraw(100, amount)}")
        } catch (e: InsufficientFundsException) {
            println("refused, short by ${e.shortBy}")
        } catch (e: IllegalArgumentException) {
            println("bad request: ${e.message}")
        } finally {
            println("done with $amount")
        }
    }
}

Output က new balance: 70၊ done with 30၊ ပြီးတော့ bad request: amount must be positive, got -5၊ done with -5၊ နောက်ဆုံး refused, short by 400 နဲ့ done with 500 ပါ။ တစ်ကြိမ်စီအတွက် finally ကြောင့် done with ... က ဘယ်လမ်းကြောင်းနဲ့ ပြီးပြီးမှာ ပါလာတာ သတိပြုပါ။

require၊ check နဲ့ error ကို လက်တွေ့ကြည့်ခြင်း

အောက်က helper က block တစ်ခု run ပြီး ထွက်လာတဲ့ exception ရဲ့ class နာမည်နဲ့ message ကို print ထုတ်ပါတယ်။ ဒါကြောင့် function တစ်ခုချင်းစီက ဘာ exception ကို ပစ်လဲ ကိုယ်တိုင် မျက်စိနဲ့ မြင်နိုင်ပါတယ်၊ message မပေးခဲ့ရင် default message က ဘာဖြစ်လဲဆိုတာပါ။

preconditions.kt
fun describeFailure(block: () -> Unit) {
    val error = runCatching(block).exceptionOrNull()
    println("${error?.javaClass?.simpleName}: ${error?.message}")
}

class Door(private var open: Boolean = false) {
    fun lock() {
        check(!open) { "cannot lock an open door" }
    }

    fun openIt() { open = true }
}

fun main() {
    describeFailure { require(false) { "bad argument" } }
    describeFailure { check(false) { "bad state" } }
    describeFailure { error("impossible branch") }
    describeFailure { requireNotNull(null as String?) { "name is required" } }
    describeFailure { "12x".toInt() }
    describeFailure { listOf(1).first { it > 5 } }
    describeFailure { Door().apply { openIt() }.lock() }
    describeFailure { require(false) }
    describeFailure { check(false) }
}

Output ကိုးကြောင်းမှာ IllegalArgumentException: bad argument၊ IllegalStateException: bad state၊ IllegalStateException: impossible branch၊ IllegalArgumentException: name is required တို့ ပါပြီး NumberFormatException နဲ့ NoSuchElementException က standard library ကိုယ်တိုင် ပစ်တာတွေပါ။ Door.lock ကတော့ IllegalStateException: cannot lock an open door ပါ။ နောက်ဆုံး နှစ်ကြောင်းက message မပေးတဲ့အတွက် Failed requirement. နဲ့ Check failed. ဆိုတဲ့ ဘာမှ မပြောပြတဲ့ default တွေကို ပြပါတယ်။

ဘယ် failure အတွက် ဘယ် tool လဲ

Toolအကောင်းဆုံးသတိထားစရာ
Exceptionbug၊ ကျိုးသွားတဲ့ precondition နဲ့ အနီးမှာ ဘယ်သူမှ ပြင်မရတဲ့ failuresignature မှာ မမြင်ရဘူး၊ checked exception မရှိဘူး
Result<T>parse ဒါမှမဟုတ် lookup လို မျှော်လင့်ထားတဲ့၊ နီးကပ်တဲ့ failure (error တစ်မျိုး)runCatching က Throwable ကို ဖမ်းတယ်၊ CancellationException အပါအဝင်
Sealed typeခေါ်သူတွေက တစ်ခုစီကို မတူအောင် ကိုင်ရမယ့် ရလဒ်နာမည်ရှိတာ အများကြီးအစမှာ code များတယ်၊ case အသစ်က when တိုင်းကို ထိတယ်

runCatching က Exception ပဲ မဟုတ်ဘဲ Throwable အားလုံးကို ဖမ်းပါတယ်၊ coroutine ထဲမှာ ဆိုရင် CancellationException ကိုပါ ဖမ်းမိလို့ cancel လုပ်တာ အလုပ်မလုပ်တော့တဲ့အထိ ဖြစ်စေနိုင်ပါတယ်။ runCatching block တွေကို သေးသေးနဲ့ နီးနီးထားပြီး မကိုင်တွယ်နိုင်တာကို ပြန်ပစ်ပါ။

လက်တွေ့ project တွေမှာ

လက်တွေ့ project တွေမှာ ဒီ tool တွေကို ဘယ်မှာ တွေ့ရလဲ

Service တိုင်းမှာ အပြင်လောကနဲ့ သင့် code တွေ့ဆုံတဲ့ နယ်နိမိတ်ရှိပြီး ဒီ tool တွေက အဲဒီနေရာမှာ အရေးအကြီးဆုံးပါ။ Repository က network ဒါမှမဟုတ် database call ကို ထုပ်ပြီး exception ကို Result ဒါမှမဟုတ် sealed UiState အဖြစ် ပြောင်းပေးလို့ screen က exception အကြမ်းကို မမြင်ရပါဘူး။ Android view model တွေက Loading၊ Ready နဲ့ Failed လို state တွေကို ဖော်ပြပြီး Compose က exhaustive when နဲ့ render လုပ်တာမို့ နောက်မှထည့်တဲ့ state အသစ်က screen တိုင်းကို ကိုင်ဖို့ တွန်းအားပေးပါတယ်။ Backend handler တွေက request body ကို require နဲ့ စစ်၊ domain exception တွေကို HTTP status code အဖြစ် နေရာတစ်ခုတည်းမှာ map လုပ်ပြီး ကျန် code ကို type ပါတဲ့ ရလဒ်တွေ ပြန်ပေးပါတယ်။

Layer တစ်ခုစီအတွက် convention တစ်ခုကို ရွေးပြီး ရေးမှတ်ထားပါ။ အသုံးများတဲ့ ခွဲခြမ်းနည်းက domain ထဲက bug နဲ့ ကျိုးသွားတဲ့ invariant အတွက် exception၊ တစ်နည်းတည်းနဲ့ fail ဖြစ်နိုင်တဲ့ I/O အတွက် Result၊ ရလဒ်တစ်ခုစီအတွက် ခေါ်သူတွေ မတူအောင် တုံ့ပြန်ရမယ်ဆိုရင် sealed type ပါ။

  • Parse နဲ့ validation: runCatching ကနေ Result<T> ရပြီး စည်းကမ်းတိုင်းအတွက် require ရှိရင် မှားတဲ့ input တစ်ခုစီအတွက် error message တစ်ခုစီ ရပါတယ်။
  • UI state: Loading၊ Ready၊ Failed ပါတဲ့ sealed interface က 'screen က ဘာပြမလဲ' ဆိုတာကို exhaustive when တစ်ခု ဖြစ်စေပါတယ်။
  • ငွေပေးချေမှုနဲ့ order: Paid၊ Declined၊ Offline လို နာမည်ရှိတဲ့ ရလဒ်တွေက ငြင်းပယ်ခံရတဲ့ ကတ်နဲ့ ပျက်နေတဲ့ network ကို မရောအောင် ခွဲပေးပါတယ်။

အမှားများ

Failure handling မှာ ဖြစ်လေ့ရှိတဲ့ အမှားများ

Sealed type ပေါ်က when မှာ else ထည့်ခြင်း

Catch-all else က compile ဖြစ်ပေမဲ့ exhaustiveness စစ်ဆေးမှုကို ပိတ်လိုက်ပါတယ်: နောက်ပိုင်း Triangle subtype အသစ်ထည့်ရင် when က else ထဲ တိတ်တိတ်လေး ကျပြီး compile error မပေးဘဲ fallback တန်ဖိုး (တွက်ချက်မှုမှာ 0.0) ကို ပြန်ပေးပါတယ်။ else မပါရင် compiler က 'when' expression must be exhaustive. Add the 'is Triangle' branch or an 'else' branch. လို့ ပြောပေးပါတယ်၊ ဒါက bug ကို run မလုပ်ခင် ဖမ်းပေးတာပါ။

require နဲ့ check ကို ရောခြင်း၊ message မပေးခြင်း

require က argument အတွက် (IllegalArgumentException)၊ check က state အတွက် (IllegalStateException) ပါ၊ ရောသုံးရင် ဖမ်းသူက မှားတဲ့ catch ကို ရောက်ပါတယ်။ Message မပေးရင် exception က Failed requirement. ဒါမှမဟုတ် Check failed. လို့ပဲ ပြောပါတယ်၊ ဘာမှားလဲ မသိရပါဘူး။ require(amount > 0) { "amount must be positive, got $amount" } လို message lambda ကို အမြဲပေးပါ။

Failure ကို မျိုချပြီး အဖြေကို ဖုံးကွယ်ခြင်း

catch (e: Exception) { return 0 } ဒါမှမဟုတ် runCatching ရလဒ်ကို ဘယ်တော့မှ မဖတ်တာက bug ကို မှားတဲ့ data အဖြစ် ပြောင်းပစ်ပါတယ်: port 0 ကို အမှန်လို့ ယူဆပြီး အလုပ်ဆက်သွားပါတယ်။ ကိုင်တွယ်နိုင်တဲ့ အတိအကျ exception ကိုပဲ catch လုပ်ပါ၊ ကျန်တာတွေ ဆက်ပြန့်ပါစေ၊ fallback သုံးရင်တောင် log ရေးပါ။ runCatching အပြီး တန်းပြီး getOrThrow ခေါ်တာက ဘာမှ မထပ်ဖြည့်ပါဘူး၊ ပစ်ခွင့်ပေးလိုက်ရင် တူတူပါပဲ။

Best Practices

Best practices

  • require နဲ့ check မှာ message lambda ကို အမြဲပေးပါ: condition မှားမှသာ တည်ဆောက်ပါတယ်။
  • ကိုင်တွယ်နိုင်တဲ့ အတိအကျဆုံး exception (ဥပမာ NumberFormatException) ကို catch လုပ်ပြီး ကျန်တာကို ဆက်ပြန့်ခွင့်ပေးပါ။
  • Subtype တွေက state မမျှသုံးရင် sealed class ထက် sealed interface ကို ကြိုက်ပြီး တစ်ခုတည်းသော instance အတွက် data object သုံးပါ။
  • Exception ကို နယ်နိမိတ်မှာ တစ်ကြိမ်ပဲ Result ဒါမှမဟုတ် sealed type အဖြစ် ပြောင်းပြီး domain အတွင်းမှာ type ပါတဲ့ ရလဒ်ကို ပေးပို့ပါ။

Mini challenge

Mini challenge: ရလဒ်သုံးမျိုးရှိတဲ့ login

Login စစ်ဆေးမှုတစ်ခုကို ပုံဖော်ပါ။ LoginResult က Welcome(user)၊ WrongPassword(attemptsLeft) နဲ့ Locked ပါတဲ့ sealed interface ဖြစ်ပါတယ်။ login() က user နာမည် blank ဖြစ်ရင် IllegalArgumentException ကို (require နဲ့) ပစ်ပြီး ကျန်ရင် LoginResult ပြန်ပေးရပါမယ်။ သီးခြားအနေနဲ့ 0..130 အပြင်က အရာအားလုံးကို ပယ်တဲ့ parseAge(text): Result<Int> ကို ရေးပြီး ရလဒ်နှစ်ခုလုံးကို exhaustive when နဲ့ ၊ onSuccess/onFailure နဲ့ ပြပါ။

  • LoginResult sealed interface မှာ Welcome၊ WrongPassword နဲ့ Locked (data object) ပါရမယ်
  • login(user, password, failedBefore) က blank name အတွက် require သုံးပြီး failedBefore >= 3 ဆိုရင် Locked ပြန်ရမယ်
  • show(result) ကို else မပါတဲ့ exhaustive when နဲ့ ရေးရမယ်
  • parseAge က runCatching နဲ့ require သုံးရမယ်၊ "34"၊ "-4"၊ "abc" တစ်ခုစီကို onSuccess/onFailure နဲ့ print ထုတ်ရမယ်
login.kt
// TODO: sealed interface LoginResult: Welcome(user), WrongPassword(attemptsLeft), Locked

val passwords = mapOf("ada" to "pw-ada", "bo" to "pw-bo")

// TODO: require a non-blank user; Locked after 3 failures; Welcome when the password
// matches; otherwise WrongPassword with the attempts that are left
fun login(user: String, password: String, failedBefore: Int): LoginResult {
    TODO()
}

// TODO: wrap the parsing in runCatching and reject ages outside 0..130 with require
fun parseAge(text: String): Result<Int> {
    TODO()
}

// TODO: an exhaustive when over LoginResult, with no else branch
fun show(result: LoginResult): String {
    TODO()
}

fun main() {
    // TODO: show a successful login, a wrong password and a locked account
    // TODO: call login with a blank user inside runCatching and print the message
    // TODO: parse "34", "-4" and "abc"; print accepted or rejected for each
}

ရလဒ်: welcome, ada၊ wrong password, 1 attempts left နဲ့ account locked ကို print ထုတ်ပြီး blank user -> user name is blank ကို ထုတ်ပါတယ်။ နောက်ဆုံးမှာ 34 accepted as 34၊ -4 rejected: age -4 is not realistic နဲ့ abc rejected: For input string: "abc" ဆိုတဲ့ line တွေ ပါပါတယ်။

အရိပ်အမြွက် ကြည့်ရန်

when { ... } ကို condition စာရင်အဖြစ် သုံးပြီး ပထမ branch က failedBefore >= 3 ဖြစ်ရမယ်။ attemptsLeft အတွက် 2 - failedBefore လို့ သုံးနိုင်ပါတယ်။ parseAge အတွက် runCatching ထဲမှာ toInt() ကို အရင်ခေါ်ပြီး require(age in 0..130) { ... } နဲ့ စစ်ပါ၊ ပြီးတော့ parseAge(text).onSuccess { ... }.onFailure { ... } ကို chain လုပ်ပါ။

အဖြေ ကြည့်ရန်
login.kt
sealed interface LoginResult {
    data class Welcome(val user: String) : LoginResult
    data class WrongPassword(val attemptsLeft: Int) : LoginResult
    data object Locked : LoginResult
}

val passwords = mapOf("ada" to "pw-ada", "bo" to "pw-bo")

fun login(user: String, password: String, failedBefore: Int): LoginResult {
    require(user.isNotBlank()) { "user name is blank" }
    return when {
        failedBefore >= 3 -> LoginResult.Locked
        passwords[user] == password -> LoginResult.Welcome(user)
        else -> LoginResult.WrongPassword(attemptsLeft = 2 - failedBefore)
    }
}

fun parseAge(text: String): Result<Int> = runCatching {
    val age = text.trim().toInt()
    require(age in 0..130) { "age $age is not realistic" }
    age
}

fun show(result: LoginResult): String = when (result) {
    is LoginResult.Welcome -> "welcome, ${result.user}"
    is LoginResult.WrongPassword -> "wrong password, ${result.attemptsLeft} attempts left"
    LoginResult.Locked -> "account locked"
}

fun main() {
    println(show(login("ada", "pw-ada", failedBefore = 0)))
    println(show(login("ada", "oops", failedBefore = 1)))
    println(show(login("ada", "pw-ada", failedBefore = 3)))

    val blank = runCatching { login(" ", "x", 0) }
    println("blank user -> ${blank.exceptionOrNull()?.message}")

    for (text in listOf("34", "-4", "abc")) {
        parseAge(text)
            .onSuccess { println("$text accepted as $it") }
            .onFailure { println("$text rejected: ${it.message}") }
    }
}

Quick Quiz 1 / 3

check(balance >= amount) { "too low" } ရဲ့ condition မှား ရင် ဘာ exception ကို ပစ်မလဲ?

Quick Quiz 2 / 3

sealed interface Shape မှာ Circle နဲ့ Square ရှိပြီး Triangle ကို နောက်မှ ထပ်ထည့်ပါတယ်။ else မပါဘဲ Circle နဲ့ Square ကိုပဲ ကိုင်တဲ့ when (shape) expression က ဘာဖြစ်မလဲ?

Quick Quiz 3 / 3

runCatching { "12x".toInt() }.getOrElse { 0 } ရဲ့ တန်ဖိုးက ဘာလဲ?

မှတ်ထားရမယ့် အချက်များ

  • Exception က bug နဲ့ ကျိုးသွားတဲ့ precondition အတွက်ပါ၊ custom exception က ဒေတာသယ်ပြီး require က IllegalArgumentException၊ check နဲ့ error က IllegalStateException ပစ်ပါတယ်။
  • Result<T> နဲ့ runCatching က မျှော်လင့်ထားတဲ့ failure ကို value အဖြစ် ပြောင်းပြီး getOrElse၊ getOrNull နဲ့ fold နဲ့ ဖတ်ပါတယ်။
  • Sealed interface က ရလဒ်တွေကို စာရင်းပိတ်ပေးပြီး else မပါတဲ့ when က ကိစ္စတိုင်းကို ကိုင်ကြောင်း compiler က စစ်ပေးပါတယ်။
  • when မှာ else ထည့်ရင် အဲဒီစစ်ဆေးမှုကို ဖျက်မိနိုင်ပြီး Exception ကို မျိုချတာက အကြောင်းရင်းကို ဖုံးကွယ်ပါတယ်။

Kotlin language guide — Kotlin

နောက်ဆုံးပြင်ဆင်ရက်

Progress ကို ဤ browser (ဤစက်) တွင်သာ သိမ်းထားပါသည်။ အခြားစက်များနှင့် sync မလုပ်ပါ။

ဤသင်ခန်းစာတွင် အမှားတွေ့ပါက အကြောင်းကြားရန်သင့် email app ကို ဤသင်ခန်းစာလိပ်စာ ဖြည့်ပြီးသားဖြင့် ဖွင့်ပေးပါမည် — သင်ကိုယ်တိုင် ပို့မှသာ ပို့မည်ဖြစ်သည်။

Sealed Types, Exceptions & Result | Thuta Learning