Immutability

This lesson explains the concept of immutability and immutable variables.

What is immutability? #

We have seen that variables represent concepts in programs. The interactions of these concepts are achieved by expressions that change the values of those variables:

// Pay the bill
totalPrice = calculateAmount(itemPrices);
moneyInWallet -= totalPrice; 
moneyAtMerchant += totalPrice;
  • Some concepts are immutable by definition. For example, there are always seven days in a week, the math constant Pi (π) never changes, the list of natural languages supported by a program may be fixed and small (e.g. only English and Turkish), etc.

  • If every variable were modifiable, then any piece of code in the program could potentially modify it. Even if there was no reason to modify a variable in operation there would be no guarantee that this would not happen by accident.

Programs are difficult to read and maintain when there are no immutability guarantees. For example, consider a function called retire(office, worker) that retires a worker of an office. All variables passed as parameters in functions are not modified by the function. However, just by looking at the function call, we cannot determine which variables are changed, and which are left unchanged.

The concept of immutability helps with understanding parts of programs by guaranteeing that certain operations do not change certain variables. It also reduces the risk of some types of ...