Mutability & Constants
01. What is a Mutability & Constants?
Mutability defines whether the content or state of a variable can be altered after it is created. A variable is mutable if its memory cells can be overwritten or its properties modified, andimmutable (or constant) if its value is fixed.
A Constant is a variable whose binding and/or value cannot be reassigned or modified. Constants enhance safety by preventing accidental changes to configuration values, limits, and invariant properties.
02. Key Characteristics
- Re-assignment vs. Value Mutation: Re-assignment changes what memory address the variable points to. Value mutation changes the actual contents stored at that address.
- Compile-Time vs. Runtime Constants: Compile-time constants are computed during compilation and optimized directly into the machine code (e.g., C++
constexpr). Runtime constants are computed at runtime but locked once initialized (e.g., Javafinal, JSconst). - Shallow Immutability: In object-oriented and dynamic languages, constant keywords typically protect only the variable reference from being re-assigned. The properties inside the referenced object can often still be mutated.
03. How Languages Represent It
At the system level, constants are represented and protected in various ways:
- Read-Only Memory Segment (.rodata): Compilers put global constants directly into dedicated read-only segments of the executable binary. Any attempt to write to this memory segment triggers a hardware page-fault exception and crashes the program.
- Compiler Checks: For local constant variables, compilers track const status inside the symbol table. The compiler raises error flags during compilation if it detects code path changes targeting these variables, meaning no machine code is ever generated for the violation.
04. Language Comparison
How different languages enforce constant variables and manage value mutation:
- Python: Lacks actual constant variables. Developer convention uses capital letter naming to represent variables that should not be changed. However, Python has built-in immutable data types such as tuples and strings.
- Java: Employs the
finalkeyword. Re-assigning a final variable causes a compiler error. It only protects the reference; list objects and fields remain mutable unless explicitly wrapped in unmodifiable collections. - JavaScript: Uses
constfor block-scoped read-only bindings. Attempts to reassign throw aTypeError. To achieve true immutability for objects, you must callObject.freeze(). - C / C++: Employs the
constqualifier. C++ also supportsconstexprto declare variables that must be evaluated and optimized at compile-time.
05. Code Examples
Select a tab below to see how mutability and constants are handled:
# Python does not support native read-only variables.
# Conventionally, we use CAPITALIZED_NAMES to denote constants.
DATABASE_URL = "localhost:5432"
# Note: Python does NOT prevent you from modifying this variable!
DATABASE_URL = "localhost:3306"
# However, Python does have immutable data types (e.g. strings, numbers, tuples)
coords = (40.7128, -74.0060)
# coords[0] = 34.0522 // TypeError: 'tuple' object does not support item assignment
# Mutable data types (e.g. lists, dicts) can be mutated freely
scores = [90, 85]
scores.append(95) // Allowed!06. Key Differences
Key comparative differences regarding variable constants and mutability:
| Language | Constant Keyword | Enforcement Level | Deep Object Immutability |
|---|---|---|---|
| Python | None (Convention only) | None (Allowed at runtime) | Requires immutable types (e.g., tuples) |
| Java | final | Compile-Time | No (Object state remains mutable) |
| JavaScript | const | Runtime (Throws error on reassignment) | No (Object state remains mutable unless frozen) |
| C | const / #define | Compile-Time | No (Pointers can bypass const constraint via cast) |
| C++ | const / constexpr | Compile-Time | No (unless using const member function qualifiers) |
07. Common Mistakes
1. Confusing Reference Immutability with Value Immutability
In JavaScript and Java, declaring const obj = { score: 10 } or final List list = ...only prevents re-assigning the variable. It does NOT prevent code from modifying properties or elements:obj.score = 20 is completely valid! To protect values, use immutable collections in Java or Object.freeze() in JavaScript.
2. Casting Away const-ness in C/C++
Using const_cast in C++ to strip const qualifiers off a pointer and write to it leads toUndefined Behavior if the underlying object was declared const. The program may crash or behave unpredictably if the compiler placed that value in read-only memory.
3. Defining Global Constants as Modifiable Conventions in Python
Because Python does not enforce capital names at runtime, other files importing a constant can accidentally overwrite it:config.API_KEY = "new_value". If true immutability is required, wrap properties inside a read-only class property or use NamedTuples.