Immutability in FP(Functional Programming)/Scala


Immutability is a key concept in FP.
Scala follows this as the default approach for variables in their programs.

Benefits/Advantages of immutable's are:
  1. They don't have complex state spaces, that change over time; easier to construct, test and use
  1. Can pass the objects around quite freely
  1. No data corruption because of thread safe; that means no synchronization issues; automatically thread safe,
  2. Makes safe hash table keys - for e.g.  If mutable object is placed into the HashSet, then modified, the object may not be found when you look into the HashSet. In other words, immutable objects are good Map keys and Set elements, since they don't change once created
  3. Makes easier to parallelize the program, as there are no conflicts among objects.
  4. The internal state of the program is consistent, even if you have exceptions.
  5. References to immutable objects can be cached as they are not going to be changed.
  6.  Execution speed up:
    With immutable objects, success or failure based on mutability is forever resolved once the object is constructed. That means less checks in runtime and more optimization from compiler, which gives faster execution of your code as a result.

No side effects, No invalid objects state and Failure atomicity

Best practice: classes should be immutable unless there is a very good reason to make it mutable, if a class can't be made immutable, limit its mutability as much as possible.

In distributed systems, immutability makes it easier to parallelize, re-compute on failure(resilient)/fault tolerance and cache.

Disadvantages:
Sometimes copying the large objects, where an update could be done in its place, in some cases it could be awkward to express and also cause performance bottleneck.

Comments

Popular posts from this blog

Implicits @ brief