Immutable Data Patterns
Returning New State
Compute the next state instead of mutating.
new-state-label
Rather than mutating a variable, immutable code computes a new value and a label describing the change. The original value stays available for comparison.
Returning New State
NewStateLabel.scala
Replay: real traced execution (multi-file project)
object Main {
def main(args: Array[String]): Unit = {
val deposit = 50
val balance = 100
val newBalance = balance + deposit
val state = if (newBalance > balance) "grew" else "same"
println("balance=" + balance)
println("newBalance=" + newBalance)
println("state=" + state)
}
}
object Main {
def main(args: Array[String]): Unit = {
val deposit = 0
val balance = 100
val newBalance = balance + deposit
val state = if (newBalance > balance) "grew" else "same"
println("balance=" + balance)
println("newBalance=" + newBalance)
println("state=" + state)
}
}
object Main {
def main(args: Array[String]): Unit = {
val deposit = 200
val balance = 100
val newBalance = balance + deposit
val state = if (newBalance > balance) "grew" else "same"
println("balance=" + balance)
println("newBalance=" + newBalance)
println("state=" + state)
}
}
deposit ← 50, balance ← 100, newBalance ← 150, state ← grew
1object Main {2 def main(args: Array[String]): Unit = {3 val deposit→ 50 = 50 //@deposit=0, 2004 val balance→ 100 = 1005 val newBalance→ 150 = balance100 + deposit506 val state→ grew = if (newBalance150 > balance100) "grew" else "same"78 println("balance=" + balance100)9 println("newBalance=" + newBalance150)10 println("state=" + stategrew)11 }12}outputbalance=100 newBalance=150 state=grew
deposit ← 0, balance ← 100, newBalance ← 100, state ← same
1object Main {2 def main(args: Array[String]): Unit = {3 val deposit→ 0 = 04 val balance→ 100 = 1005 val newBalance→ 100 = balance100 + deposit06 val state→ same = if (newBalance100 > balance100) "grew" else "same"78 println("balance=" + balance100)9 println("newBalance=" + newBalance100)10 println("state=" + statesame)11 }12}outputbalance=100 newBalance=100 state=same
deposit ← 200, balance ← 100, newBalance ← 300, state ← grew
1object Main {2 def main(args: Array[String]): Unit = {3 val deposit→ 200 = 2004 val balance→ 100 = 1005 val newBalance→ 300 = balance100 + deposit2006 val state→ grew = if (newBalance300 > balance100) "grew" else "same"78 println("balance=" + balance100)9 println("newBalance=" + newBalance300)10 println("state=" + stategrew)11 }12}outputbalance=100 newBalance=300 state=grew