2 ms·
I don't really understand what it's for or why I'd use it. I don't "get" immutable variables. Anyone I ask for an explanation just says "but it means that if yo
by Gordonjcp 4y ago
I don't really understand what it's for or why I'd use it. I don't "get" immutable variables. Anyone I ask for an explanation just says "but it means that if you do something to the variable it doesn't change the value for other parts of the program" which just seems a bit daft to me.
What's an actual concrete use case of this? Where specifically would I use immutable variables to make my code better?
- belmont_sup 4y agoIt’s all about handling state in a careful manner. A helpful consequence of immutability is that it makes concurrent and parallel programming easier. Take Erlang/Elixir. The main reason it’s able to share state between processes so easily is because it completely copies values from one process into another’s mailbox. Compiler guarantees you don’t pass a reference. If it were the same memory, two processes could mutate and unwittingly break one another. Another helpful aspect are the patterns of code you end up writing. It’s common in Node and C#, even Go, to pass a mutable context or stateful object with a bunch of hands reaching in to read and write. Because you can naturally do this, you naturally also tend to program like this. Cue data access issues again. But if you guarantee immutability at the runtime level, it changes how you write code. You tend to write functions in a “transformer” / pipeline style. there’re great examples of open source codebases to read from that exhibit this. See a typical F#, Haskell, and presumably Scala web api codebase, and see how they handle state.
- roflyear 4y agoWell, in Python for example there is the classic bug where if you change a dictionary in some function, it changes everywhere else. Can't do that with immutable data. It is easy to avoid, but if you can't do it anyway, the potential for bugs go away.