The building blocks of FP: pure functions, immutability, and Referential transparency -Part 2-

This is a continuation of https://scalatorblog.wordpress.com/2019/04/17/the-building-blocks-of-fp-referential-transparency-immutability-and-pure-functions-part-1/

Mutant are not always on your side

Immutability

First a definition is in order :
“In object-oriented and functional programming, an immutable object (unchangeable[1] object) is an object whose state cannot be modified after it is created.[2] This is in contrast to a mutable object (changeable object), which can be modified after it is created.” dixit wikipedia
So once an immutable variable is created it can not be modified, if we declare a variable lets say

val immutableAcc = 0
immutableAcc = 3

the compiler should show you a nice error.

So Why immutable :
As shown previously immutability contribute to the creation of pure functions, if a variable is immutable, when a function access it and try to modify it, it will create a copy and thus it has full control over it.
But the importance of immutability is way beyond functional programing it serves multiple purposes:
reduce cognitive burden: having dozens of variable can be already hard to keep track of, now imagine all these variables accessed in different places and modified, it becomes a huge mess; our code becomes less readable prone to bugs and less attractive

data sharing optimization: an optimization technique used by some compiler, assigning the same multiple label to the same memory cell. might seem like a negligible thing to do for an INT, but scale it up to bigger data structure

concurrency and race conditions: if you are in the development business a race condition is your worst nightmare, usually it happens when you have a shared ressource (variable, file….) between 2 process running concurrently, one of them is reading the ressource the other is updating it, depending on the order of execution you might get different result on the read.
Now multiple tricks can be set up, like locks or semaphores, but eliminating the shared state using immutable variables, is a clean and safe way to go

keeping a timeline: now using a immutable variables let us draw a timeline in the operations, we can easily track the operation involved in the transformation.
as a user on Quora put it :
At every moment, the past exists as read-only, immutable chain of events (what has happened has happened), whereas new events (what is happening now) are “appended” at the end of timeline.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s