This question came to mind when following some tutorials on Scala, but i think is interesting in general when it comes to functional programming.
I am unsure about the importance of immutability in FP. I can think of 2 different cases:
1) A class method does not return the actual fields but a copy of them. For example if we have a class Dog which we need to keep immutable, then its function:
getToys() { return new ArrayList(this.toys); }
instead of:
getToys() { return this.toys; }
This case makes perfect sense to me, in the 2nd case client code could actually corrupt the object. My skepticism lies in the 2nd case:
2) In Scala and most other FP languages we prefer a recursive call:
sum(x: List[Int], acc: Int) {
if(x.isEmpty) return acc;
sum(x.tail, acc + x.head);
}
against a traditional for loop incrementing an accumulator. The reasoning is that this accumulator is a mutable variable.
That variable is never exposed outside the function so why care to make it immutable?
EDIT:
It seems like the most important best practice is referential transparency and not strict immutability, meaning roughly that we don't care about mutable state as long as it is not discoverable by client code. However people still claim that even when mutable state affects local variables (as in my 1st example) the code is more readable or easier to reason about.
Personally, i would argue that a loop is more readable than a recursion.
So the real question is: Why is code using immutable variables considered easier to read / reason about?