EDDYMENS

Published today

What Are Immutable Variables And Objects?

Table of contents

In programming, immutability means that once a variable [→] or object is created, its value cannot be changed. If you need a different value, you must create a new variable or object instead of modifying the existing one.

Why is this useful?

  • Predictability – Since immutable variables never change by other developers or the program, their values stay the same throughout the program, making the code more predictable.
  • Thread Safety – Immutable objects are safe to use in multi-threaded programs because they can't be modified unexpectedly.

Examples

In many programming languages, you can create immutable variables using special keywords.

Example in JavaScript (using const):

01: const name = "Ama"; 02: name = "Kwesi"; // Error

Example in Python (using tuples):

01: coordinates = (10, 20) 02: coordinates[0] = 30 # Error: TypeError: 'tuple' object does not support item assignment

Immutable Objects in Object-Oriented Programming

In object-oriented languages, immutable objects can be created so that their internal state cannot change after instantiation.

Example in Java

01: final class Person { 02: private final String name; // final keyword ensures immutability 03: 04: public Person(String name) { 05: this.name = name; 06: } 07: 08: public String getName() { 09: return name; 10: } 11: }

Once a Person object is created, the name field cannot be changed.

Here is another article you might like 😊 What Is Edge Computing?