⬅ Previous Topic
Lambda FunctionsNext Topic ⮕
Closures and Higher-Order Functions⬅ Previous Topic
Lambda FunctionsNext Topic ⮕
Closures and Higher-Order FunctionsImmutability 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.
Let’s look at the difference between mutable and immutable behavior using pseudocode.
# Mutable example
list = [1, 2, 3]
append(list, 4)
print(list)
[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)
[1, 2, 3, 4] [1, 2, 3]
Here, the original list
remains unchanged, and a new list newList
is created with the added element.
A pure function is a function that satisfies two main conditions:
# Impure function
counter = 0
function increment():
counter = counter + 1
return counter
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
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.
Answer: Pure functions make your code predictable and easy to test. They help you build robust systems by minimizing hidden dependencies and side effects.
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.
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.
⬅ Previous Topic
Lambda FunctionsNext Topic ⮕
Closures and Higher-Order FunctionsYou can support this website with a contribution of your choice.
When making a contribution, mention your name, and programguru.org in the message. Your name shall be displayed in the sponsors list.