Understand
Immutability and Pure Functions



What is Immutability?

Immutability means that once a value is created, it cannot be changed. Instead of modifying existing data, new data structures are created with the desired changes. This concept helps in making code more predictable, safer, and easier to debug.

Why is Immutability Important?

Example: Mutable vs Immutable Behavior

Let’s look at the difference between mutable and immutable behavior using pseudocode.

# Mutable example
list = [1, 2, 3]
append(list, 4)
print(list)

Output:

[1, 2, 3, 4]

This directly modifies the original list. Any other function using list will now see the changed version, which might cause unexpected behavior.

# Immutable example
list = [1, 2, 3]
newList = list + [4]
print(newList)
print(list)

Output:

[1, 2, 3, 4]
[1, 2, 3]

Here, the original list remains unchanged, and a new list newList is created with the added element.

What are Pure Functions?

A pure function is a function that satisfies two main conditions:

Example: Pure vs Impure Functions

# Impure function
counter = 0

function increment():
    counter = counter + 1
    return counter

Output:

Each call to increment() returns a different value: 1, 2, 3...

This function is impure because it relies on and modifies a variable outside its scope.

# Pure function
function add(a, b):
    return a + b

Output:

add(2, 3) => 5
add(2, 3) => 5  # always returns the same result

This function is pure. It depends only on its input and doesn’t affect anything outside itself.

Question: Why should we care about pure functions?

Answer: Pure functions make your code predictable and easy to test. They help you build robust systems by minimizing hidden dependencies and side effects.

Question: How does immutability support functional programming?

Answer: Functional programming emphasizes avoiding state changes. Immutability ensures data is not accidentally altered, which fits perfectly with this philosophy and helps create pure functions.

Best Practices

Conclusion

Immutability and pure functions are at the heart of clean and functional programming. Embracing these principles leads to code that is predictable, easy to test, and bug-resistant. In large systems or team environments, it greatly simplifies reasoning about program behavior.



Welcome to ProgramGuru

Sign up to start your journey with us

Support ProgramGuru.org

Mention your name, and programguru.org in the message. Your name shall be displayed in the sponsers list.

PayPal

UPI

PhonePe QR

MALLIKARJUNA M