CodeGym /행동 /Kotlin SELF /Property delegates: Delegates.observable as a reaction to...

Property delegates: Delegates.observable as a reaction to assignment

Kotlin SELF
레벨 32, 레슨 4
사용 가능

1. Introduction

Cheoeum Delegates.observable reul bomyeon dangyeonhan jilmuneul hagetjyo: “by gat-eun eotteon magic-i piryohae? na-neun set(value) reul sseugo geogi-eseo modeun geol check/log hamyeon doe잖아?” Jilmuneun jeongdanghamnida. Dapdo jeongjikhamnida: observable eun assign-e daehae jungangjipjung-jeok-euro reaction hagoseo, gateun code reul yeoreo method na setter-e heundeureo nohji anko sip-eul ttae yuyonghamnida — yeg: logging, change counting, “object changed” flag seoljeong.

Cheoeum-e gyeonggye reul hwaksilhage haejabseumnida: i geos-eun overview lecture imnida. Uri-neun jasin-ui delegate reul mandeulji do ango, advanced topic (eotteohge getValue/setValue ga guseongdoeneunji, reflection, multithreading detail) ro deureogaji anseumnida. Uri-neun standard library-ui junbi-doen tool 로서 Delegates.observable reul jasine itge sayonghaneun geos-eul baewobnida.

Properties-eseo by ga tteonanun geos

Delegated property-ui syntax-neun ireoke boimnida: val/var name: Type by <expression>. I geos-eun daeryak ireoke ilkseumnida: “i property-ui read wa ( var 면) write reul dareun object — delegate — ga cheori한다.” Kotlin documentation-eseoneun i geos-eul ireoke seolmyeonghamnida: property accessor-ga delegate method (getValue() wa setValue()) 로 “forward” 된다.

Jeoneun lecture reul tteoollyeobomyeon, by lazy { ... } do delegate imnida (neomu in-giga iss-eoseo teukbyeolhae boineun geos ppun). Delegates.observable eun dareun jongsin-ui delegate: 값을 저장hago, mae assign dwie handler reul hoechulhamnida.

“Gapsag-i” saeroun syntax-ro ttwieodeureoganeun neukkim-eul jul-igi wihae, jageun guide reul hana duryeobnida:

Mechanism What it solves When code runs Has cache?
set(value)
Write control (validation/normalization) Every assignment Depends on you
computed property (
get() = ...
)
Compute a view/representation Every read No
by lazy { ... }
Lazy evaluation First read access Yes (built-in)
Delegates.observable(...)
Reaction to changes Every assignment (after write) Yes (delegate stores the current value)

2. How Delegates.observable works

Basic contract and when the handler fires

Delegates.observable eun initial value 와 change handler reul badseumnida. Handler-neun property-e 값을 assign hal ttae마다 hoechuldoemyeo, jungyohan nuance-ga issseumnida: assign-i imi ir-eonan dwie hoechuldoendaneun geot imnida.

Handler-eneun parameter-ga 3gae: “property description”, old value, new value. Code-eseoneun botong ireoke boimnida:

import kotlin.properties.Delegates

class User {
    var name: String by Delegates.observable("<no name>") { _, old, new ->
        println("$old -> $new") // <no name> -> Alice, затем Alice -> Bob
    }
}

fun main() {
    val u = User()
    u.name = "Alice"
    u.name = "Bob"
}

Juyeoui: handler-ui cheot beonjjae parameter-neun _ 로 bakkwotseumnida. I geos-eun parameter-ga pilyohaji an-eumyeon code reul deukgi swipge haneun ilbanjeog practice imnida.

“After assignment” eseo baro follow 되는 du 가지 important consequence-ga issseumnida.

Cheot째, handler naebu-eseo geu property jache reul read hamyeon imi 새 값(이미 write 된 값)을 eodneun geos-eul bol su issseumnida. Pyeonri hajiman, “먼저 알림, 그다음 write” reul gidahaetdamyeon hon란스러울 su issseumnida.

Dul째, observable eun 잘못된 값을 “막는” 자리-ga 아닙니다. Assign 을 차단해야 한다면, geu-geon dareun tool (oneul-eun 주제-ga peojineun geos-eul pihae ttabolloji anseumnida) 입니다.

The first handler parameter and why it’s sometimes useful

Handler-ui cheot beonjjae parameter-neun property reul seolmyeonghaneun object (siljiljeog-euro: “property metadata”) imnida. Documentation-eun i parameter-ga old/new 와 hamkke handler 로 jeondaldoendago boyeojumnida.

Uri-ga reflection-eul gipi baeuji anassjiman (geureol pilyo eopsseumnida), siljeon-eseo sseul su issneun han gaji-neun gajigo gal su issseumnida: property-eneun name-i issseumnida. Yeoreo ga-ui observable property-ga issgo message style-eul tong-ilhago sip-eul ttae, debugging log-e yuyonghal su issseumnida.

Wallet-eul jom deo mal-i manhge mandeureobopseumnida:

import kotlin.properties.Delegates

class Wallet {
    var balanceCents: Int by Delegates.observable(0) { prop, old, new ->
        println("${prop.name}: $old -> $new") // balanceCents: 0 -> 100
    }
        private set

    fun deposit(cents: Int) {
        require(cents > 0) { "deposit must be > 0" }
        balanceCents += cents
    }
}

Ne, geonman 보면 “jogeum-ui magic” cheoreom boimnida. Hajiman siljeon-eseoneun prop.name reul “kkumjikhage ttarawa jun bonus” ro batadeurimyeon doemnida: sseugo sip-eumyeon ssego, sileumyeon _ reul ssemyon doemnida.

A small peek under the hood: why there is prop$delegate

Delegate reul jageun jeongdo lo ihaehagi wihan mini overview imnida. Kotlin-eun delegation-eul hamyeon botong delegate reul 저장haneun sumeun field reul generate 하고, property accessor-neun geu delegate-ui method reul hoechulhamnida. Documentation-eun prop$delegate cheoreom boineun field-ga natananeun 예시 로 i geos-eul boyeojumnida.

Neomu dan순화hamyeon, daeryak ireoke sangsanghal su issseumnida:

obj.prop = value
   ↓
делегат.setValue(obj, описание_свойства, value)
   ↓
делегат записывает новое значение
   ↓
делегат вызывает обработчик observable (old/new)

Geuraeseo observable eun “eoneo-e ingebuilthae” boineun geoscheoreom 느껴집니다: silje-ro-neun standard library-ui junbi-doen delegate il ppunigo, by syntax-neun delegation-eul wihan eoneo jiwon imnida.

Yeogiseo jungyohan geon gwadohaji anneun geot imnida. Gae-ryeom jeongdo ihae-neun yuyonghajiman, “na-man-ui delegate reul eotteohge sseu나” 는 jeonhi dareun juje imnida. Oneul-eun geugoseo-ro gaji anhseumnida.

3. Practice: where observable helps and where it gets in the way

Mini budget tracker: log balance changes

Yemul-i “jinsang” eul pihae, gyesokhae seo-gyehaneun 가상 app-eul sseobopseumnida: 간단한 budget tracker (wallet) 로, balance 와 deposit/withdraw operation 이 issseumnida. Uri-neun imi state encapsulation-eul 할 jul 압니다: balance-neun 바로 바꿀 수 없고, invariant-reul jikinun method 를 통해서만 바뀝니다.

Wallet class 를 만들go, balance change-e daehae reaction-eul ddeokbutyeo bobmyeon: console-e balance change log-reul print 하겠습니다. I geos-eun observable ui typical scenario imnida: business logic reul dae체haneun geos-i anira, assignment-e daehae observe 하는 것.

import kotlin.properties.Delegates

class Wallet {
    var balanceCents: Int by Delegates.observable(0) { _, old, new ->
        println("balance: $old -> $new") // например: balance: 0 -> 500
    }
        private set

    fun deposit(cents: Int) {
        require(cents > 0) { "deposit must be > 0" }
        balanceCents += cents
    }
}

main 에서 확인해 봅시다:

fun main() {
    val w = Wallet()
    w.deposit(500) // balance: 0 -> 500
    w.deposit(250) // balance: 500 -> 750
}

Yeogiseo du 가지 yuyonghan geosi dongsi-e il-eonabnida. Cheot째, 올바른 design-eul 유지했습니다: 바깥에서 balance 를 바꿀 수 없습니다 (private set). Dul째, logging logic-i property jache-e “붙어서” method마다 duplication-doeji 않습니다.

observable and encapsulation: where rules and checks should live

Choe-dae 빈도의 초보자 실수-neun observable reul bogo 신나서 geu 안에 business logic 를 몽땅 넣어버리는 것입니다: “새 값이 나쁘면 되돌리자”, “balance 가 minus 면 고치자” 등. Munje-neun observable eun assignment 뒤에 reaction 한다는 점입니다. 즉 이미 값을 써버린 다음에 “뭔가를 고치기” 시작합니다.

Deo baramjikhan geon, jeon-e 설계한 위치에 규칙을 두는 것입니다: state 를 바꾸는 method 에 두거나, require(...) 를 포함한 setter 에 둡니다. 그리고 observable 은 side effect: logging, change counter, “dirty” flag seoljeong 같은 용도로 남겨둡니다.

Yeg-eul deu-myeon, deposit 와 withdraw method 를 만들go minus 로 내려가는 것을 금지합니다. 그리고 observable 에서는 state ga 바뀌었다는 사실만 표시합니다.

import kotlin.properties.Delegates

class Wallet {
    var isDirty: Boolean = false
        private set

    var balanceCents: Int by Delegates.observable(0) { _, old, new ->
        if (old != new) isDirty = true
    }
        private set

    fun withdraw(cents: Int) {
        require(cents > 0) { "withdraw must be > 0" }
        require(balanceCents >= cents) { "not enough money" }
        balanceCents -= cents
    }
}

Jageun run:

fun main() {
    val w = Wallet()
    println(w.isDirty) // false
    w.withdraw(0)      // IllegalArgumentException (withdraw must be > 0)
}

Yeogiseo jungyohan idea: “gyeolgwa reul 치유” 하는 게 아니라, “mi리 방지” 합니다. observable eun 변경 사실만 기록하지, correctness 를 지휘하지 않습니다.

observable vs a regular setter: what to choose

observable eun setter-ui dae체제가 아닙니다. Dareun tool 입니다.

Mokjeok-i string normalize (예: trim, case conversion), range check, invariant 유지 라면, setter(또는 method) ga botong deo 명확하고 직선적입니다. Mokjeok-i change-e daehae reaction (log, count, notify) 이라면, observable ga code 를 deo compact hage mandeul 때가 많습니다.

Gae-sanghaebopsida: app-eseo “notification volume level” i issgo, 0 에서 10 까지 값만 저장하고, 바뀔 때마다 log 를 찍고 싶습니다. 규칙은 method 에 두고, log 는 observable 에 둡니다.

import kotlin.properties.Delegates

class NotificationSettings {
    var volume: Int by Delegates.observable(5) { _, old, new ->
        println("volume: $old -> $new")
    }
        private set

    fun setVolume(x: Int) {
        require(x in 0..10) { "volume must be in 0..10" }
        volume = x
    }
}

Ije class-ui “contract” ga 잘 읽힙니다: setVolume eun 변경의 유일한 문이고, volume eun 읽기만 가능하며, logging 은 중앙집중화되었습니다.

observable in real life: change counter

Keun project-eseo observable eun UI 와 자주 연결됩니다: “field ga 바뀌면 화면을 업데이트해.” Hajiman console app-eseo do pyeonrihal su issseumnida.

Yeg-eul deu-myeon, balance change 횟수를 세고 싶다고 해봅시다. Geuraeseo majimak-e “session 동안 N 번의 financial operation 이 있었다” reul 보여줍니다. 물론 method마다 counter 를 increment 할 수 있습니다. Hajiman future-e operation 이 늘어나면 (discount, transfer, fee 등), eodiseo 하나 빼먹고 counter update 를 안 해서 “왜 통계가 틀리냐” 같은 일이 생깁니다.

observable 로 property change 사실에 counter 를 묶을 수 있습니다:

import kotlin.properties.Delegates

class Wallet {
    var changeCount: Int = 0
        private set

    var balanceCents: Int by Delegates.observable(0) { _, old, new ->
        if (old != new) changeCount++
    }
        private set

    fun deposit(cents: Int) {
        require(cents > 0) { "deposit must be > 0" }
        balanceCents += cents
    }
}

Check:

fun main() {
    val w = Wallet()
    w.deposit(100)
    w.deposit(100)
    println(w.changeCount) // 2
}

Ne, i geos-do side effect imnida. Hajiman localized 되어 있고 명확합니다: “balance 가 변경될 때마다 counter 를 올린다.”

4. Common mistakes when working with Delegates.observable

Mistake #1: put business logic and correctness rules inside the observable handler.
Handler-eseo modeun geol haryeogo hagi swip습니다: range check, rollback, object “fix” 등. Munje-neun handler ga assignment 뒤에 불린다는 점이라, 이미 바뀐 state 를 대상으로 작업하게 됩니다. 훨씬 신뢰할 수 있는 방법은 invariant 를 method (deposit/withdraw) 나 require(...) 가 있는 setter 에 두고, observable 에는 logging 과 간단한 reaction 만 남기는 것입니다.

Mistake #2: accidentally create recursion — assign the observed property inside the handler.
Handler-eseo balanceCents = ... 같은 일을 하면, assign 이 다시 일어나고 handler 가 다시 호출되고… 결국 StackOverflowError 까지 갈 수 있습니다. 값을 “고쳐야” 한다면, 대부분은 “assign 전에 validate” 하는 쪽으로 design 을 바꿔야 한다는 신호입니다.

Mistake #3: forget the handler runs even when assigning the same value.
observable eun assignment 사실 자체에 반응합니다. x = x 를 해도 handler 가 불릴 수 있습니다. Geuraeseo change 를 세거나 isDirty flag 를 세팅한다면, 거의 항상 old 와 new 를 비교하고 “진짜 변경” 에만 반응하는 것이 좋습니다: if (old != new) ...

Mistake #4: turn observable into a hidden logger that always makes noise.
Handler-eseo println eul sseuneun geon 학습 예제에서는 편하지만, 실무에서는 log 가 금방 noise 로 변합니다. 학습 앱에서도 점차 습관을 들이는 게 좋습니다: logging 은 끌 수 있게 만들거나(최소한 flag 로), 정말 중요한 것만 찍거나, 출력량을 제한하세요.

Mistake #5: expect observable to replace encapsulation.
Gakkeum “변경을 감시하니까 public var 로 열어두고 아무나 바꾸게 해도 handler 에서 통제하면 되지” 라고 생각하기 쉽습니다. Geureon jeobgeun-eun wiheomhamnida. Observation 은 access restriction 을 대체하지 못합니다. 밖에서 바꾸면 안 되는 property 라면, private set 으로 막고 method 를 통해 변경하세요. observable 은 깔끔한 “sensor” 로 두고, 유일한 “guard” 로 만들지 마세요.

1
과제
Kotlin SELF, 레벨 32, 레슨 4
잠금
nickname 변경 로그
nickname 변경 로그
1
과제
Kotlin SELF, 레벨 32, 레슨 4
잠금
스마트 볼륨
스마트 볼륨
1
과제
Kotlin SELF, 레벨 32, 레슨 4
잠금
메모 초안
메모 초안
1
과제
Kotlin SELF, 레벨 32, 레슨 4
잠금
설정 로그
설정 로그
1
설문조사/퀴즈
속성과 캡슐화, 레벨 32, 레슨 4
사용 불가능
속성과 캡슐화
속성과 캡슐화
코멘트
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION