Back to series
· 11 min read

Immutability & Mutability


I. Basic Concepts of Immutability and Mutability

Immutability and mutability describe whether data is allowed to change state after it is created.

Mutability: After an object or piece of data is created, its internal state is allowed to be modified.

Immutability: After an object or piece of data is created, its internal state is not allowed to be modified. When a different state is needed, a new object or value is usually created.

For example:

// Mutable object
const user = {
    name: "Alice",
    age: 20
};

user.age = 21;

// Immutable value
const name = "Alice";

// String operations return a new string
const newName = name.toUpperCase();

Two concepts need to be distinguished here:

  • const restricts reassignment of the variable; it does not mean the object's internals are immutable.
  • Immutability describes the ability to modify the data itself, not whether a variable can be rebound.

For example:

const user = {
    name: "Alice"
};

// Object properties can be modified
user.name = "Bob";

// Rebinding the variable is not allowed
user = {};

The first operation is legal; the second operation will cause an error.

Therefore, to determine whether an object is mutable, you cannot rely solely on whether it is declared with const, final, let, or similar declaration methods.

1.1 Mutable and Immutable Objects

Comparison Dimension Mutable Objects Immutable Objects
Whether state can be modified after creation Allowed Not allowed
Modification method Modify internal state directly Create a new value or object
Object identity Usually the same before and after modification Usually a new object after modification
Memory usage Can reuse the original object May create new objects
Concurrent sharing Synchronization needs to be considered Usually easier to share safely
State tracking Need to pay attention to modification history State changes are clearer
Typical applications Caches, state containers, mutable collections Configuration, value objects, functional data

It should be noted that immutable objects do not mean the underlying memory will never change. For example, garbage collection, runtime-internal caching, and lazy initialization may change the physical state of an object, but they do not necessarily change its externally observable logical state.

II. Implementation Mechanisms of Mutability

Mutable objects allow their internal state to be modified after creation.

For example, in Java:

class User {
    String name;
    int age;
}

User user = new User();

user.name = "Alice";
user.age = 20;

user.age = 21;

After an object is created, the program can access it through a reference and modify its fields.

From a memory-model perspective, this can be abstracted as:

variable user
    |
    v
User object
    |
    +-- name = "Alice"
    |
    +-- age = 20

After modification:

variable user
    |
    v
User object
    |
    +-- name = "Alice"
    |
    +-- age = 21

The object's identity has not changed, but its internal state has changed.

2.1 In-place Mutation

In-place mutation means directly modifying an existing object rather than creating a new object to replace it.

For example, in Python:

numbers = [1, 2, 3]

numbers.append(4)

print(numbers)
# [1, 2, 3, 4]

append() directly modifies the original list.

Now consider a dictionary:

user = {
    "name": "Alice",
    "age": 20
}

user["age"] = 21

The dictionary object is still the original object; only its internal data has changed.

In-place mutation usually has the following characteristics:

  • It can reuse existing objects.
  • It reduces some overhead from object creation and copying.
  • It may affect other code that shares the same object.
  • Aliasing, concurrency, and state consistency need to be considered.

2.2 Reference Sharing Issues with Mutable Objects

When multiple variables reference the same mutable object, if the object is modified through any one of those references, the change can be observed through the other references.

For example:

user_a = {
    "name": "Alice",
    "age": 20
}

user_b = user_a

user_b["age"] = 21

print(user_a["age"])
# 21

Here, the object was not copied; instead, two references pointing to the same object were created.

flowchart TD
    A["variable user_a"] --> C["the same User object"]
    B["variable user_b"] --> C
    C --> D["name = Alice"]
    C --> E["age = 20"]
    F["modify age through user_b"] --> G["age = 21"]
    G --> C

    style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
    style B fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
    style C fill:#E5F4EC,stroke:#A3CBB5,color:#334155
    style D fill:#F3EDFC,stroke:#C4B2E3,color:#334155
    style E fill:#F3EDFC,stroke:#C4B2E3,color:#334155
    style F fill:#FFF5DE,stroke:#E8D29A,color:#334155
    style G fill:#FFF5DE,stroke:#E8D29A,color:#334155
    linkStyle default stroke:#A3B8AC,stroke-width:1.5px

This phenomenon is called aliasing.

Aliasing itself is not an error, but it increases the complexity of state management.

When an object is shared by multiple modules, modifications may affect other modules, leading to:

  • Implicit state changes.
  • Data sources that are difficult to trace.
  • Errors that are difficult to reproduce.
  • Concurrent access conflicts.
  • Inconsistent cached data.

2.3 Shallow Copy and Deep Copy

To avoid sharing the same mutable object, you can create a new object by copying.

However, copying does not necessarily mean that all nested objects are copied.

Shallow Copy

A shallow copy copies only the first level of an object's structure; nested objects inside may still share references.

Python:

import copy

user_a = {
    "name": "Alice",
    "profile": {
        "age": 20
    }
}

user_b = copy.copy(user_a)

user_b["name"] = "Bob"
user_b["profile"]["age"] = 21

print(user_a["name"])          # Alice
print(user_a["profile"]["age"]) # 21

user_a and user_b are two different outer dictionaries, but their internal profile still points to the same dictionary.

Deep Copy

A deep copy recursively copies nested objects, building an independent data structure as much as possible.

import copy

user_a = {
    "name": "Alice",
    "profile": {
        "age": 20
    }
}

user_b = copy.deepcopy(user_a)

user_b["profile"]["age"] = 21

print(user_a["profile"]["age"]) # 20

The difference between the two copying methods:

Comparison Aspect Shallow Copy Deep Copy
Outer object New object New object
Nested objects Usually shared Usually recursively copied
Copy cost Lower Higher
Memory usage Less More
Circular references No need to recursively process internal structures Needs to handle circular references
Use cases Only need to isolate the outer structure Need to isolate the entire object graph

Deep copy cannot always be used directly in all cases either. Resource objects such as file handles, locks, network connections, and database connections usually cannot simply be copied to obtain an independent and valid resource state.

III. Implementation Mechanisms of Immutability

Once an immutable object is created, external code is not allowed to modify its logical state.

For example, in Java:

public final class User {
    private final String name;
    private final int age;

    public User(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public int getAge() {
        return age;
    }
}

This class has the following characteristics:

  • The class uses final and cannot be inherited.
  • Fields use private to avoid direct external access.
  • Fields use final and can only be assigned during initialization.
  • No setters are provided to modify fields.
  • After construction is complete, field values no longer change.

When using:

User user = new User("Alice", 20);

If you need a user whose age is 21, you usually create a new object:

User updated = new User(
    user.getName(),
    21
);

The original user object has not changed.

3.1 State changes of immutable objects

Immutable objects do not modify themselves directly; instead, they express new state by creating new objects.

flowchart TD
    A["Create User object"] --> B["User(Alice, 20)"]
    B --> C["Need to modify age"]
    C --> D["Create new object"]
    D --> E["User(Alice, 21)"]
    B --> F["Original object remains unchanged"]
    E --> G["Use new object"]

    style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
    style B fill:#E5F4EC,stroke:#A3CBB5,color:#334155
    style C fill:#FFF5DE,stroke:#E8D29A,color:#334155
    style D fill:#F3EDFC,stroke:#C4B2E3,color:#334155
    style E fill:#E5F4EC,stroke:#A3CBB5,color:#334155
    style F fill:#E8EDF2,stroke:#B8C3CE,color:#334155
    style G fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
    linkStyle default stroke:#A3B8AC,stroke-width:1.5px

This approach makes state changes explicit, which helps track data provenance and build predictable program logic.

3.2 Deep issues with immutable objects

The fact that a field of an object cannot be reassigned does not mean the entire object is necessarily immutable.

For example:

public final class User {
    private final List<String> roles;

    public User(List<String> roles) {
        this.roles = roles;
    }

    public List<String> getRoles() {
        return roles;
    }
}

Although roles uses final, the list itself can still be modified:

List<String> roles = new ArrayList<>();
roles.add("USER");

User user = new User(roles);

user.getRoles().add("ADMIN");

At this point, the object's internal state has already changed.

The reason is:

final restricts the reference variable from being reassigned to point to another list; it does not restrict modification of the list object itself.

In addition, the constructor directly stores a mutable list passed in from outside, which also allows external code to modify the object's internal state.

3.3 Defensive Copying

To prevent external references from affecting an object's internal state, defensive copying can be performed at input and output boundaries.

public final class User {
    private final List<String> roles;

    public User(List<String> roles) {
        this.roles = List.copyOf(roles);
    }

    public List<String> getRoles() {
        return roles;
    }
}

List.copyOf() creates an unmodifiable list view or copy; whether it reuses an existing unmodifiable list is determined by the implementation.

For the string elements here, because String itself is immutable, the expected immutability can be satisfied.

However, if the list elements are mutable objects, List.copyOf() only guarantees that the list structure is unmodifiable; it does not recursively freeze the element objects.

For example:

List<UserProfile> profiles = ...;

List<UserProfile> copied = List.copyOf(profiles);

The caller may still modify the elements' internal state through other references to UserProfile.

Therefore:

Immutability must consider the entire reachable object graph, not just the outermost fields of the object.

4. Different Levels of Immutability

Immutability is not a simple binary concept. In practical programming, it can be understood at different levels.

4.1 Variables cannot be reassigned

Immutable variable binding means a variable cannot be rebound to another value or object.

For example, in Java:

final int count = 10;

The following operation is not allowed:

count = 20;

JavaScript:

const count = 10;

Likewise, it cannot be reassigned.

But immutable variable binding does not mean the object is immutable.

const user = {
    name: "Alice"
};

user.name = "Bob";

Here the variable binding has not changed, but the state of the object has.

4.2 Object Immutability

Object immutability means that once an object is created, its observable logical state cannot be modified from the outside.

For example, in Java:

String name = "Alice";

Strings are immutable objects.

String newName = name.replace("A", "B");

After execution, the original string is still "Alice", and the new string is "Blice".

4.3 Collection Structural Immutability

Collection structural immutability means that the number, order, or membership of the elements in a collection cannot be modified.

For example, in Java:

List<String> names = List.of(
    "Alice",
    "Bob"
);

Try executing:

names.add("Charlie");

It will throw UnsupportedOperationException.

However, if the collection holds mutable objects, the elements themselves may still change.

4.4 Deep Immutability

Deep immutability requires that neither the object nor any of its reachable internal objects can undergo observable state changes.

For example:

User
 ├── name: String
 ├── age: int
 └── roles: List<String>

If:

  • User itself cannot have its fields modified.
  • The roles collection cannot have elements added or removed.
  • The elements in the collection are also immutable values.

Only then can the entire object structure achieve deep immutability.

In real-world engineering, deep immutability is usually more valuable than shallow immutability, but it also requires stricter object design and copying strategies.

V. Immutability and Mutability in Different Programming Languages

Different languages express mutability through different mechanisms.

5.1 Java: final and Immutable Classes

Java uses final to restrict variable reassignment, and it can also be combined with class design to build immutable objects.

final class Point {
    private final int x;
    private final int y;

    Point(int x, int y) {
        this.x = x;
        this.y = y;
    }

    int getX() {
        return x;
    }

    int getY() {
        return y;
    }
}

A distinction must be made:

  • final variable: cannot be reassigned.
  • final reference: cannot point to another object.
  • final field: cannot be assigned again after initialization.
  • final class: cannot be inherited.
  • Immutable object: the logical state of the entire object cannot be modified.

These concepts are related, but not equivalent.

5.2 JavaScript: const, Object.freeze and Structural Sharing

In JavaScript, const only restricts rebinding of the variable.

const user = {
    name: "Alice"
};

user.name = "Bob";

If you want to prevent an object's properties from being modified, you can use:

const user = Object.freeze({
    name: "Alice",
    age: 20
});

But Object.freeze() only performs a shallow freeze by default.

const user = Object.freeze({
    name: "Alice",
    profile: {
        age: 20
    }
});

user.profile.age = 21;

Nested objects can still be modified.

For complex state, recursive freezing or immutable data structure libraries can be used, but cyclic references, object types, and performance costs need to be taken into account.

5.3 Python: Mutable and Immutable Built-in Types

Common immutable types in Python:

  • int
  • float
  • bool
  • str
  • tuple
  • frozenset

Common mutable types:

  • list
  • dict
  • set
  • Most custom class instances

For example:

name = "Alice"

name = name + " Smith"

String operations do not modify the original string; they create a new string object and rebind the variable.

Now look at lists:

numbers = [1, 2, 3]

numbers.append(4)

The list itself has changed.

Special attention is needed here: although tuples are immutable, they can contain mutable objects.

data = ([1, 2], 3)

data[0].append(4)

print(data)
# ([1, 2, 4], 3)

The tuple's element bindings have not changed, but the state of the inner list has changed.

5.4 C++: const and Reference Restrictions

C++ provides const to restrict modification of an object through a particular access path.

const int value = 10;

For objects:

class User {
public:
    void setAge(int value) {
        age = value;
    }

private:
    int age = 20;
};

const User user;

Non-const member functions cannot be called through a const object.

C++ also supports const references:

User user;

const User& ref = user;

What is restricted here is modification through ref; it does not mean the original object is immutable through other access paths.

user.setAge(30);

The object can still be modified through a non-const reference.

This reflects an important characteristic of C++:

const-correctness is primarily a constraint at the level of access paths and the type system; it does not necessarily mean the object is globally immutable.

5.5 Rust: Ownership and Mutable Borrowing

Rust tightly integrates mutability with ownership and borrowing rules.

By default, variables are immutable:

let value = 10;

When modification is needed, the variable must be declared as mut:

let mut value = 10;

value = 20;

For references:

let mut value = 10;

let reference = &value;

reference is an immutable reference.

A mutable reference:

let mut value = 10;

let reference = &mut value;

*reference = 20;

The core Rust borrowing rules include:

  • Multiple immutable references can exist.
  • A mutable reference and other active references cannot exist at the same time.
  • A mutable reference requires the borrowed data itself to be mutable.
  • Ownership rules ensure that references do not outlive the data's valid lifetime.

Such constraints can reduce data races and illegal modifications at compile time.

5.6 Go: Mutability of Values and Pointers

Go variables can be reassigned by default:

value := 10
value = 20

For structs:

type User struct {
    Name string
    Age  int
}

user := User{
    Name: "Alice",
    Age:  20,
}

user.Age = 21

Go allows fields to be modified directly through a struct value, and also through a pointer:

userPtr := &user
userPtr.Age = 22

Go does not have a general-purpose keyword exactly equivalent to Java's final or Rust's default immutable binding.

In Go, permission to modify objects is usually controlled through encapsulation, interface design, and data-copying conventions.

5.7 Comparison of Mechanisms Across Languages

Language Immutability mechanism Mutability mechanism
Java final, immutable classes, unmodifiable collections Ordinary fields, mutable collections
JavaScript const, Object.freeze(), immutable data structures let, modification of object properties
Python Immutable built-in types, frozen data classes list, dict, ordinary objects
C++ const, constexpr Ordinary objects, non-const references
Rust Immutable bindings by default, immutable borrows mut, mutable borrows
Go Encapsulation, value semantics, read-only interface conventions Ordinary variables, pointers, and mutable fields

Six. Immutability, Value Semantics, and Reference Semantics

Immutability is often discussed together with value types and reference types, but they are not the same concept.

6.1 Value Semantics

Value semantics emphasize that data behaves as an independent value when it is assigned, passed, or copied.

For example:

a := 10
b := a

b = 20

fmt.Println(a) // 10

Modifying b does not affect a.

For a struct:

type Point struct {
    X int
    Y int
}

a := Point{X: 1, Y: 2}
b := a

b.X = 100

a.X is still 1, because assigning a struct copies its fields.

But if the struct contains a pointer, slice, or map, the underlying data may still be shared after copying.

6.2 Reference Semantics

Reference semantics emphasize that multiple variables can reference the same object.

For example, in Java:

User a = new User("Alice", 20);
User b = a;

b.setAge(21);

After modifying the object through b, what a observes is also the modified state.

6.3 The Relationship Between Immutability and Value Semantics

Immutability and value semantics are strongly related, but they are not equivalent.

Type Mutable? Example
Value semantics Immutable Integers, immutable structs
Value semantics Mutable Ordinary struct variables in Go
Reference semantics Immutable Java String
Reference semantics Mutable Java ArrayList

Immutable objects can be shared by reference because the sharing parties cannot modify their logical state.

This is also an important reason why immutable objects are suitable for caching, passing across modules, and sharing concurrently.

Seven. Immutability and Functional Programming

Functional programming emphasizes building programs through function composition and minimizing mutable state and side effects.

Immutability is one of the important foundations of functional programming.

7.1 Pure Functions

Pure functions satisfy two core characteristics:

  1. The same input always produces the same output.
  2. They produce no observable external side effects.

For example:

function add(a, b) {
    return a + b;
}

This function does not depend on external state, nor does it modify its inputs.

Now look at a non-pure function:

let total = 0;

function add(value) {
    total += value;
    return total;
}

The result depends on the external variable total, and the external state is modified.