Skip to content

In U, variables are immutable by default, but you can define mutable variables too. Mutables variables should generally have a limited scope, either as a field or as a local value. Within a limited scope, mutable variables are easier to control and are less likely to be modified in incorrect ways.

Mutability

Imperative programming languages such as C/C++ and Java involve mutable state that changes throughout execution:

  • Statements specify how to compute by changing that state
  • Functions or methods can have side effects (change outside current function body) and produce a return value. For example, reading from the command line, writing to a database, throwing an exception, are side effects.

Why not ?

Mutability gives the illusion of thinking like a machine. The fantasy of mutability is that it seems easy to reason about: "the machine does this, then this, ..." The reality of mutability is that:

  • Machines are good at large scale manipulation of states but,
  • Humans are not good at having a mental view of them as a whole. Therefore, mutability quickly becomes complex for humans, and systems become hard to design, debug, or extend.
  • Concurrency is very hard with is shared mutable data on modern hardware. If two different threads have access to the same piece of data, any update might be an undefined behavior.

Immutability

Immutability, however, frees developers from these concerns. It provides powerful ways to build correct and concurrent programs by:

  • Safely isolating data,
  • Preventing data race,
  • Allowing efficient optimization