Immutability
This lesson explains the concept of immutability and immutable variables.
We'll cover the following...
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 ...