Options and Error Handling
Guard Clauses
Clamp and label invalid numbers before using them.
guard-clauses
A guard clause checks input early and replaces a bad value with a safe one. The note records what happened so later steps stay deterministic.
Guard Clauses
GuardClauses.scala
Replay: real traced execution (multi-file project)
object Main {
def main(args: Array[String]): Unit = {
val input = 8
var safe = input
var note = "ok"
if (input < 0) {
safe = 0
note = "negative"
}
if (input == 0) {
note = "zero"
}
val ready = safe > 0
println("input=" + input)
println("note=" + note)
println("ready=" + ready)
}
}
object Main {
def main(args: Array[String]): Unit = {
val input = -4
var safe = input
var note = "ok"
if (input < 0) {
safe = 0
note = "negative"
}
if (input == 0) {
note = "zero"
}
val ready = safe > 0
println("input=" + input)
println("note=" + note)
println("ready=" + ready)
}
}
object Main {
def main(args: Array[String]): Unit = {
val input = 0
var safe = input
var note = "ok"
if (input < 0) {
safe = 0
note = "negative"
}
if (input == 0) {
note = "zero"
}
val ready = safe > 0
println("input=" + input)
println("note=" + note)
println("ready=" + ready)
}
}
input ← 8, safe ← 8, note ← ok, ready ← true
1object Main {2 def main(args: Array[String]): Unit = {3 val input→ 8 = 8 //@input=-4, 04 var safe→ 8 = input→ 85 var note→ ok = "ok"6 if (input < 0) {7 safe = 08 note = "negative"9 }10 if (input == 0) {11 note = "zero"12 }13 val ready→ true = safe8 > 01415 println("input=" + input8)16 println("note=" + noteok)17 println("ready=" + readytrue)18 }19}outputinput=8 note=ok ready=true
input ← -4, safe ← -4, note ← ok
1object Main {2 def main(args: Array[String]): Unit = {3 val input→ -4 = -44 var safe→ -4 = input→ -45 var note→ ok = "ok"6 if (input < 0) {7 safe = 0safe ← 0, note ← negative
5var note = "ok"6if (input-4 < 0) {7 safe→ 0 = 08 note→ negative = "negative"9}10if (input == 0) {ready ← false
12 }13 val ready→ false = safe0 > 01415 println("input=" + input-4)16 println("note=" + notenegative)17 println("ready=" + readyfalse)18 }19}outputinput=-4 note=negative ready=false
input ← 0, safe ← 0, note ← ok
1object Main {2 def main(args: Array[String]): Unit = {3 val input→ 0 = 04 var safe→ 0 = input→ 05 var note→ ok = "ok"6 if (input < 0) {7 safe = 0note ← zero
9}10if (input0 == 0) {11 note→ zero = "zero"12}13val ready = safe > 0ready ← false
12 }13 val ready→ false = safe0 > 01415 println("input=" + input0)16 println("note=" + notezero)17 println("ready=" + readyfalse)18 }19}outputinput=0 note=zero ready=false