Immutability: Why is it important?

Why is it important? Watch this video to get the answer:

In Object oriented programming the state of the application is shared, if you have several functions trying to change a data value at the same time it might lead to unexpected errors because the value they thought they would receive is changed by other processes. (Thanks to mutable data)

When we update a value in OOP we usually do something like this:

a = [1]
a.append(2)

This would update the original list, which is the opposite of what happens in elixir. In elixir each time we “change” a data value what’s really happening is we’re creating a new data value by copying the old one and then creating a new data structure, the original remaining intact.

What this means is that we can have several programs depending on the same data structure and be certain that none of them will affect the others because they can’t even change the original value!

Conventional languages are adding functionality inspired by functional languages but still it’s hard to take full advantage of them when you’re having the imperative paradigm (mutable state) clashing with the functional paradigm in the same language, for example to do concurrency they use locks so that only one process can modify a data value at a time.

In elixir all data is immutable. Doesn’t matter how complex or simple the data structure is, the data is always immutable and that’s perfect for parallel processes.

Remember: transforming data (copying it and making a new data structure) is different from modifying the data(taking the existing data structure and changing it)

Elixir reminds us of this with its syntax, instead of modifying objects like:

Carlos.age = 23

we transform data like:

Time.get_age(1996, current_year=2019)

and get 23 as a result.

References

Programming Elixir 1.6 Part 1, Section 3: Immutability

Learn Functional Programming with Elixir, Chapter 1: Thinking Functionally


Leave a Reply

Your email address will not be published. Required fields are marked *