1. Wae ttaeron-eun modeun ge jeong-sang-in cheokhaneun geotboda baro muneojineun ge joteun-ga
Mankeum han beonirado “sam jueil-e han beon, mokyoil-e, geureonde dal-i Yeomsojari-e iss-eul ttaeman” gat-i byeollo-ui jogeon-eseo man balhyeon doeneun bug-reul bwan jeogi issdamyeon, ije i munje-reul algo issseumnida: peurogeuraem-i eodikkaseo jinjeonghan gireul beoseonji han참 jeon-e i탈haetneunde, geureondo kyesok silhaengdoemyeonseo modeun ge jeong-sang-in cheokhamnida. Fail-fast neun seollaga doendaneun ge hwaksilhae jineun sungan, baro silhaeng-eul meomchuneun seupgwan imnida: deo isang logigi uimi eops-eumyeon geugeollo kkeut. Igeon hwasin gyeongbo jangchi gatseumnida: jam-eul banganhajiman, jam-eul jal su eopsdaneun geol hwaksilhae juseyo.
Uri-ui ipryeok/peosing/yuhyo-seong geomsa yutiliti-eseoneun i미 부드러운 jeollyag-eul taekhaessseumnida: yesang ganeunghan deiteo oryu-e daehaseoneun null eul banhwanhamnida. Hajiman dareun jongnyu-ui munje do issseumnida: hamso sayong oryu imnida. Yereumyeon, beomwi validator reul jageul haennunde, nugunga (jaju neun baro nado) silsuro min=100, max=10 cheoreom neomeo-otdaneun geot. Igeon “sayongja-ga jalmosseon ipryeok” i anira “peurogeuraemeo-ga gyeonggye reul bakkwo beoryeotda” imnida. Geureomyeon null eun doeeo boji anseumnida: oryu-reul joyonghi mandeureo beoribnida.
Dae-rak i chaireul jeongnihae bopsida:
| Sanghwang | Yesi | Uri seon-taek (ilbanjeog) ban-eung |
|---|---|---|
| Yesang ganeunghan deiteo munje (sayongja ipryeok) | Susja daesin "qwerty" reul ipryeok | null eul banhwan, ssenario-ga seolmyeonghago eotteokge halji gyeoljeong |
| Jeonjedo chogeon wiban (peurogeuraemeo oryu) | Beomwi-reul min > max ro jeondal | Fail-fast: require/check |
Dujeonja gyeso ui kye이스-reul wihae Kotlin-eun “precondition functions” in require() wa check() reul jepgonghamnida — i deul-eun jogeon-i seongnipaji aneumyeon jadong-euro 예외를 deonjigo silhaeng-eul jungdanhamnida.
2. Precondition: geuge mwoya?
Precondition-eun hamso-ui juyo logig-i sijakdoegi jeon-e cham-ijyeoya haneun gyuchik imnida. Geureoji aneumyeon, geu hamso-neun jeongsangjeog-euro dongjakhal u-mu-ga eopsseumnida. Igeon “modeun geol 다 geomsa” haneun geosi anira, 잘못된 호출-eul bang-ehaneun geot-e gakkapseumnida. Geurigo jungyohan jeom: precondition-eun “sayongja ipryeok yuhyo-seong geomsa” ga 아닙니다. Sayongja-neun jeopgeunhae uri hamso-reul jikjeop bureuji anhgo, teukjeong munjayeol-eul ipryeokhamyeon uri-ga geugeol eotteoke cheorihalji gyeoljeonghamnida.
Precondition-eun mirae-ui nae 자신-ege jageun memo reul sseuneun deusi jeong-uihamyeon pyeonhamnida: “I hamso-neun ... hal ttaeman dongjak한다.” Jog-eon-i kkaejimyeon — peurogeuraem-i baro, keuge, geurigo ihae hal su issneun message-wa hamkke muneojige 하세요. Bul편hajiman aju jeongjikhamnida: “ibryeok chogeon-i jalmosdwaeseo deo isang jinhanghal su eopsda.”
Precondition dui jongnyu: argument wa state
Precondition-eun bo통 du gae jongnyu-ro 나누-go, Kotlin-eun geu e daehae dwaejiro du gae hamso reul 따로 jepgonghamnida. I gyeonggye-neun suhakjeog-euro wanbyeokhajin 않지만, silje-ro는 seutail-eul gyesok gyeonggye-hago geomsa-reul “meongcheonghan juk” eulo mandeulji 않게 haejumnida.
Argument precondition-eun hamso-ga parameteo-reul badeul ttae, geu deul-i ol바른ji hwagin haneun geot imnida: yereumyeon min <= max, “discount 0~100”, “size > 0”. I ttae bo통 require(...) reul sseugo, wiban si IllegalArgumentException eul deonjimnida.
State precondition-eun argument-neun jeongsangcheoreom boijiman, peurogeuraem naebu-e eotteon sangtae-ga isseoseo hamso-ga geu sangtae-ga i미 junbi doeeotseul geol gidahaneun gyeong-u imnida: “session started”, “settings loaded”, “call init first”. I ttae bo통 check(...) reul sseugo, wiban si IllegalStateException eul deonjimnida.
3. require: argument geomsa + IllegalArgumentException 로 fail
require(condition) { message } neun “I hamso-reul 잘못 호출했다; argument-ga matji 않는다” 라고 malhaneun 표준 bangbeob imnida. Kotlin-eun i gyeong-u IllegalArgumentException eul deonjimnida. Igeo seuna “oru-ga jeil tteuge deureonaya haneun” sanghwang imnida: argument-ga jal못됐다면 munje-neun sayongja-ga 아니라 코드 imnida.
Jungyohan jeom: require neun “sayongja-ga 숫자 대신 munja-reul ipryeok” 같은 케이스의 도구가 아닙니다. Geureon 경우-neun i미 …OrNull gwa ssenario-level cheori-ga issseumnida. require neun “peurogeuraemeo-ga eongteonghan geol jeondalhaetda” reul 잡neun 도구입니다.
Beomwi validator: min > max bangji
Ije kkaji “susja-ga beomwi an-e inneunji” gateun validator-reul sseotjyo. Ibeon-eneun geugeollo kkeut-i anira, beomwi jache-ga 올바르게 jijeongdoeeotneunji precondition-eul chugahaebopsida.
fun validateIntInRangeOrNull(x: Int, min: Int, max: Int): Int? {
require(min <= max) { "Expected min <= max, but got min=$min, max=$max" }
if (x < min) return null
if (x > max) return null
return x
}
Yeogi-e seo hagsim cheolhak-eul bwaseyo: x ga “beomwi-reul 벗어났다” myeon geugeon yesang ganeunghan deiteo sanghwang-ira서 null. Hajiman beomwi jache-ga mal-i 안 되게 jijeongdoeeotdamyeon, geugeon “deiteo” ga 아니라 “nugunga(ama-do na) ga code-eseo silsuhaetda” imnida. Geureoni fail-fast.
Beomwi naeu susja 읽기 yutiliti
Ije ssenario-level hamso han gae-reul deo eokseumyeonseo, reading + validation-eul gyesok guchyeonghaebopsida. Iseoseo require ga teukhi yuyonghan iyu-neun, beomwi gyeonggye-neun sayongja ga 아니라 peurogeuraemeo-ga jeonghagi ttaemunimnida.
fun readIntOrNull(prompt: String): Int? {
print(prompt)
val s = readln()
return s.toIntOrNull()
}
fun readIntInRangeOrNull(prompt: String, min: Int, max: Int): Int? {
require(min <= max) { "Expected min <= max, but got min=$min, max=$max" }
val x = readIntOrNull(prompt) ?: return null
return validateIntInRangeOrNull(x, min, max)
}
Nugunga-ga readIntInRangeOrNull("Age: ", 150, 0) cheoreom bureumyeon, peurogeuraem-eun baro muneojimnida — geurigo geuge joteun geot imnida. Geureoji 않으면 “hangsang null man naoneun” isanghan ssenario-reul bogo sayongja, 키보드, geurigo “retrograde Mercury” kkaji uisimhage doemnida.
4. check: state geomsa + IllegalStateException 로 fail
check(condition) { message } neun “peurogeuraem naebu ui hyeonjae sangtae-ga jeongsang-igo, geureoji 않으면 logic error” 라고 말하는 bangbeob imnida. Kotlin-eun i gyeong-u IllegalStateException eul deonjimnida. require ga “bakkat-eseo 잘못 부른 호출” eul jabu-myeon, check neun “uri-ga uri jache-reul 궁지로 몰아넣었다” reul 잡seumnida.
Chobo sujun ui console peurogeuraem-eseo state-neun bo통 han-du gae byeonsu로 boyeo: “settings set”, “user name already entered”, “mode chosen”. Igeollo도 check ui hyogwa-reul 충bunhi bol su issseumnida.
Yesi: session-eun ban-deu-si sijakdoeeoya 한다
Maeu gyoyukjeogijiman uimi issneun yesi-reul mandeureo bopsida. “session 시작” eul 먼저 하고, geu daeum-e jilmun-eul 하는 mini peurogeuraem-eul sangsanghaebopsida.
var sessionStarted: Boolean = false
fun startSession() {
sessionStarted = true
}
fun askUserName(): String {
check(sessionStarted) { "Session not started. Call startSession() first." }
print("Your name: ")
return readln()
}
Igeo-neun sayongja-ga jal못 han geosi jeon혀 eopsseumnida. Sayongja-neun startSession() i mwonji-do moreumnida. Igeon uri naebu protocol imnida. Uri-ga 호출 순서를 어겼다면 logic error-igo, geugeol baro bogo sipeun geot imnida.
Wae yeogiseo require ga 아니고 check 인가
require(sessionStarted) 로 써도 기술적으로는 떨어집니다. 하지만 의미가 나빠집니다: IllegalArgumentException eun “argument-ga 나쁘다” 라고 suggest 하는데, munje-neun argument-ga 아니라 “peurogeuraem state-ga 잘못됐다” imnida. check ga deo jeonghwak하게 malhaego, jeonghwakham-eun joheun diagnosis ui ban imnida.
require/check message: nae 자신-ege 부끄럽지 않게 쓰기
require/checkrequire(min <= max) cheoreom message eops-i sseumyeon, exception-eun tteojiman 맥락 없이: 무엇이 전달됐는지 알 수 없습니다. Jageun peurogeuraem-eseoneun yuchuhal su issjiman, silje-ro-neun 자세한 jeongbo-reul namae doeneun jasin-ege gam사하게 됩니다.
Joheun message-neun bo통 du gae bu-bun-eul gajimnida: “mueos-eul 기대했나” 와 “mueos-eul 받았나”. Jom jansori cheoreom deull릴 수 있지만, i jansori-ga 시간 을 beoseonghamnida.
fun validateIntInRangeOrNull(x: Int, min: Int, max: Int): Int? {
require(min <= max) { "Expected min <= max, but got min=$min, max=$max" }
if (x < min) return null
if (x > max) return null
return x
}
Muneojimyeon, baro 구체적인 susja-reul bol su issseumnida. Igeo-neun beomwi-ga “직접” jeonghaejineun 게 아니라, wi-eseo eodikkaseo gyeosan doeeo 내려오는 gyeong-u-e teukhi jungyohamnida (dareun byeonsu-deulro buteo-ra do).
5. Guard clauses: if pyramid reul geuman sseugi
Chobo code (솔직히 chobo-man-eun 아니죠) reul sangsanghaeboseyo: jogeon geomsa, geu 안에 또 geomsa, 또 geomsa... “pyramid” ga doeeoseo code-ga oreunjjok 으로 밀리고, bogo it으면 머리가 아파옵니다. Guard clauses (보호/가드 검사) neun geomsa-reul 처음에 하고, mueonga jal못되면 hamso-reul baro 빠져나가는 seutail imnida. Code-ga seonhyeong-uro 바뀌어서, wi-eseo arae-ro “juyo logig-e gikeun 장애물 목록” cheoreom ilk힐 수 있습니다.
Jungyohan jeom: guard clauses-neun eoneo ui byeoldo construction-i 아닙니다. Danji if (...) return ... reul jungcheop block daesin seupgwancheoreom sseuneun geot imnida.
Before: jungcheop-do wa oreunjjok “계단”
Yereumyeon, sagaghyeong ui neobi wa nopi (1..100) reul ilggo myeonjeok-eul gyesanhago sipeun gyeong-u. Nun-i “Undo” beoteun-eul chaj게 만드는 beojeon-eun dae-rak ireohseumnida:
fun rectangleAreaScenario() {
val w = readIntOrNull("Width: ")
if (w != null) {
val h = readIntOrNull("Height: ")
if (h != null) {
if (w in 1..100) {
if (h in 1..100) {
println("Area = ${w * h}")
} else {
println("Height out of range.")
}
} else {
println("Width out of range.")
}
} else {
println("Height is not a number.")
}
} else {
println("Width is not a number.")
}
}
Code-neun daeche-ro matjiman, ilgineun matryoshka-reul ppaegineun deusi himdeumnida: modeun gyesi-reul yeoreoya, eodi-e “area” ga inneunji bo입니다.
After: guard clauses + early exit
Ije juyo uimi(“myeonjeok gyesan”) ga bba르게 보이도록, geomsa-ga pyramid reul mandeulji 않게, code-reul dasi 써bopsida.
fun rectangleAreaScenario() {
val w = readIntOrNull("Width (1..100): ") ?: run {
println("Width must be an integer.")
return
}
if (w !in 1..100) {
println("Width out of range 1..100.")
return
}
val h = readIntOrNull("Height (1..100): ") ?: run {
println("Height must be an integer.")
return
}
if (h !in 1..100) {
println("Height out of range 1..100.")
return
}
println("Area = ${w * h}") // for example: Area = 12
}
Ije ilkgi-ga eolmana pyeonhanji bwaseyo: mueonga jal못되면 baro 나가고 seolmyeong합니다. Kkeutkkaji 왔다면 modeun ge jeongsang-ira서 myeonjeok-eul gyesanhamnida.
Guard clauses wa …OrNull, require/check
Yeogiseo hon란seureoul su iss으니, jageun 도표로 jeongrihaebopsida. Uri-neun null gwa guard clauses-reul “올바른 값을 얻지 못했다” neukkim-e sseubnida. require/check
flowchart TD
A[Start of function] --> B{Is the problem expected?}
B -->|User input, format, range| C[Return null / exit via guard clause]
B -->|Function preconditions violated| D[require/check -> exception]
C --> E[Scenario decides what to print]
D --> F[Bug in code is immediately visible]
Geuligo: fail-fast haetdago 해서 null cheori-ga bul-pilyohan geon 아닙니다. Igeon dalleun jongnyu-ui munje-reul wihae jonjaehaneun du gae ui 도구입니다.
6. Mini-API-e fail-fast 심기: 조심스럽지만 확실하게
Ije jom deo “seong-in” code-uro han georeum gaja. Uri yutiliti-neun yesang ganeunghan munje-eseoneun yeojeonhi null eul banhwanhajiman, 잘못된 사용-e daehaseoneun se스로reul bang-eohage doel geot imnida. Urin yeojeonhi oneul sujun 안에서: banbok ipryeok loop eopsi, bokjaphan architecture eopsi — danji discipline imnida.
Jageun hamso set (dan순hwahajiman 일관된) 을 moaseo main() 에서 사용해 bopsida.
Jeongsanghan composition: read + validate + guard clauses
fun readIntOrNull(prompt: String): Int? {
print(prompt)
return readln().toIntOrNull()
}
fun validateIntInRangeOrNull(x: Int, min: Int, max: Int): Int? {
require(min <= max) { "Expected min <= max, but got min=$min, max=$max" }
if (x < min) return null
if (x > max) return null
return x
}
fun readIntInRangeOrNull(prompt: String, min: Int, max: Int): Int? {
require(min <= max) { "Expected min <= max, but got min=$min, max=$max" }
val x = readIntOrNull(prompt) ?: return null
return validateIntInRangeOrNull(x, min, max)
}
Jungyohage bol jeom: uri-neun du hamso-eseo require(min <= max) reul uidojeog-euro jungbokhaessseumnida. Ne, jungbok imnida. Hajiman igeon “호출 지점에서의 보험” imnida: eoneu hamso-reul bakkweo sseugeona dareuge sayonghaedodo, gakja-ga jasin-eul bang-eoham니다. Silje-ro-neun 나중에 refactor hal su 있지만, 지금은 명확함이 더 중요합니다.
main() mini-scenario: area
fun main() {
val w = readIntInRangeOrNull("Width (1..100): ", 1, 100) ?: run {
println("Invalid width.")
return
}
val h = readIntInRangeOrNull("Height (1..100): ", 1, 100) ?: run {
println("Invalid height.")
return
}
val area = w * h
println("Area = $area") // for example: Area = 12
}
Igeon “세기의 앱” 은 아니지만, seutail-eul wanbyeokhi boyeojumnida: yutiliti-neun “조용하고”, ssenario-neun “말을 하고”, precondition-eun “바보 같은 호출” 로부터 uri-reul 지켜줍니다.
check yesi: initialization eun 필수
Ije state yesi-reul han beon deo chuga해 bopsida. Han beonman limit-reul seoljeonghago, geu daeum-e geu limit-e ttaraseo 값을 읽고 싶다고 해봅시다. Yeogiseoneun “진짜 config” reul 만드는 게 아니라, check ui gaenyeom-eul boyeojuneun 게 mokjeok imnida.
var configuredMin: Int? = null
var configuredMax: Int? = null
fun configureLimits(min: Int, max: Int) {
require(min <= max) { "Expected min <= max, but got min=$min, max=$max" }
configuredMin = min
configuredMax = max
}
fun readConfiguredIntOrNull(prompt: String): Int? {
check(configuredMin != null && configuredMax != null) {
"Limits are not configured. Call configureLimits(min, max) first."
}
val min = configuredMin!!
val max = configuredMax!!
return readIntInRangeOrNull(prompt, min, max)
}
Ne, yeogien !! ga issseumnida. Isangjeogin segye-eseoneun pihaet겠지만, 지금 sujun-eseoneun dareun geosi deo jungyohamnida: check ga configuredMin gwa configuredMax i i미 seoljeongdoeeotseumnida라는 geol 보장하고, geureoji 않으면 bba르게, myeonghwakhan message 로 baro muneoj게 합니다. Gyoyuk용 yesi-eseo “state” reul boyeojuneun 데는 괜찮은 illustration imnida. Na중에-neun !! ga 덜 필요하도록 설계하는 beopdo ik힐 geos imnida.
7. Typical mistakes
Mistake #1: using require/check for ordinary invalid user input.
Sayongja-ga 200-eul ipryeokhaess-eul ttae require(x in 1..100) reul sseugo sipeun yughok-i keumnida. Hajiman geureomyeon peurogeuraem-eun modeun “틀린” ipryeok마다 muneojgo, sayongja-neun dangsin ui nerve testereul haneun gibun-i doel geos imnida. Ipryeok-e daehaseoneun daleun seutail: …OrNull + scenario-level cheori imnida.
Mistake #2: “swallowing” precondition violations via null.
Hamso-ga ol바른 parameteo-ro만 호출되어야 한다면 (예: min <= max), null eul banhwanhaneun geon 나쁜 아이디어입니다. Myeongbaekhan oryu-reul joyonghan oryu로 바꿔, 나중에 “wae 계속 null man 나오지?” reul chajneura orae 걸립니다. I런 케이스는 require 또는 check 로 baro fail-fast 해야 합니다.
Mistake #3: writing require(condition) without a message.
Gisuljeog-euro-neun dongjak하지만, diagnosis 관점-e-seo-neun geoui 쓸모 없습니다. Message-neun 기대 조건을 설명하고 실제 값을 보여줘야 합니다. Il ju il hu-eneun 무슨 검사를 했는지 기억도 안 날 텐데, min=$min, max=$max 는 도움 됩니다.
Mistake #4: mixing up require and check, and losing the meaning of the exception.
Argument yuhyo-seong-eul geomsa한다면 bo통 require + IllegalArgumentException. Naebu state-reul geomsa한다면 bo통 check + IllegalStateException. Kotlin-do i hamso-deul-eul uimi-wa exception type i dareun geos-euro 명확히 positioning 합니다.
Mistake #5: building an if pyramid instead of using guard clauses, then being afraid to touch the code.
Jungcheop if neun hamso-reul geum방 미로로 바꿔, eotteon branch-ga mueos-eul uimi하는지 잊기 쉽습니다. Guard clauses + early return eun code-reul seonhyeong으로 만들고, “jal못되면 나가고, 아니면 계속한다” reul 명확히 합니다. Ilkgi swipgo, 수정 시 logic error chance 를 줄입니다.
Mistake #6: performing checks but continuing “hoping it works anyway”.
Ttaeron if (x == null) println("Error") cheoreom sseugo도 return eul 안 해서, daeum code-ga null eul 가지고 dongjak해버리거나 잘못된 값으로 계속 진행되는 경우가 있습니다. Guard clauses ui 가치는 message reul 찍은 뒤 정말로 “나간다” 는 데 있습니다 — “geureoda bomyeon un-i 좋을지도?” 모드로 coding 하지 않게 해줍니다.
GO TO FULL VERSION