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 programming errors.
The immutability concept is expressed in D by the const and immutable keywords. Although the two words themselves are close in meaning, their responsibilities in programs are different, and they are sometimes incompatible.
const and immutable are type qualifiers. We will see inout and shared in later chapters.

Immutable variables #

Both of the terms “immutable variable” and “constant variable” are nonsensical when the word “variable” is taken literally to mean something that changes. However, in a broader sense, the word “variable” is often understood to mean any concept of a program which may be mutable or immutable.

There are three ways of defining variables that can never be mutated. enum constants, immutable variables and const variables.

enum constants #

We have seen earlier in the enum lesson that enum defines named constant values:

enum fileName = "list.txt";

As long as their values can be determined at compile time, enum variables can be initialized with return values of functions as well:

Get hands-on with 1200+ tech skills courses.