Answer the question
In order to leave comments, you need to log in
What's so good about immutability?
What's so good about being immutable ? I'm trying to find information on this topic, but all the time I come across abstract phrases like: "the ability to avoid side effects." Can you suggest a single threaded scenario/side effect example? If I have an object that needs to be accessible from different points in the program, how can functional programming help me?
Also, please do not indicate as advantages of immutability, such things as the possibility of parallelization, caching. This is all very interesting, but it's all utilitarian stuff, it doesn't treat immutability as a concept in and of itself.
Answer the question
In order to leave comments, you need to log in
Immutability is about the guarantee that you will not accidentally change the value that was passed to you from the outside.
And that the function you passed your value to won't change it.
Here's a dumb example:
let today = now().date
let tomorrow = today.addDays(1)
assert(today != tomorrow)
Well, for example, you can effectively reuse and store data structures.
for example, add 2 lists:
in the case of an immutable one, in order to create a third common list, you just need to specify links where necessary, to the first and second list - both lists will be reused, and only a couple of additional links will be added to memory (this is computationally fast and requires little memory).
in the case of mutable lists, you need to create a third one by copying all the elements of the first and second ones, which is expensive both in terms of execution time and storage space.
if you also try to make a new structure with references in a mutable structure, you may end up with such a situation that already AFTER creating a new list, when changing in the original structure, these changes will appear in your new list as an uncontrolled change that you did not perform.
As a result, since immutable structures have guarantees that they will not be changed, they can be reused when creating new data structures, while mutable ones cannot.
Imagine a ledger, the one on paper - that's an example of immutability.
The main advantages are data consistency and atomicity of operations.
Immutability simplifies composability - it's easier to put together different pieces of code if they are free from side effects. In addition, immutable code, other things being equal, is easier to read and modify.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question