3 ms·
it's precisely when values change over time that you want immutability most. Values always change over time, otherwise you could replace variables by c
by mafribe 11y ago
it's precisely when values change
over time that you want immutability
most.
Values always change over time, otherwise you could replace variables by constants.
I suggest that immutability is most useful for data that crosses into a context that you (the programmer) have no/little control over. There is nothing wrong with a bit of state, like so
def pow ( n : Int ) : Int = {
var result = 1
var i = n
while ( i > 0 ) {
result *= 2
i -= 1 }
return result }
The reason this is OK is that the state changes are local, while globally (from the outside) pow remains functional. There is no need to coordinate with other programmers, or other functions or modules, to get i and n to behave properly.
In contrast, if you pass shared state into a context that you have limited knowledge or control over (e.g. shared memory concurrency) then things become hairy.
That's why I advocate: "locally stateful, globally stateless" programming.
- bad_user 11y agoJust a note, variables are always replaceable by constants ;-) @tailrec def pow(n: Int, result: Int = 1): Int = if (n > 0) pow(n - 1, result * 2) else result But yes, mutability isn't problematic if it's well encapsulated. Works well for simple functions, but when you get to more complicated things (e.g. classes/modules) the problem is that proper encapsulation is very hard to do, sometimes next to impossible.
- mafribe 11y agoSure, we can always translate away state and pass it explicitly. Some people find some algorithms can be more naturally expressed using state. (And "some people" is a polite way of saying "alot".) The question of whether state can always be replaced by pure functions without loss of asymptotic complexity is open as of April 2016. All I wanted to point out is that there is no need of becoming a functional Taliban: if state is kept local, that's usually fine. when you get to more complicated things Yes. Then don't use it. My rule of thumb is: definition and all uses of state should be visible to the programmer without scrolling.