I\'ve read a couple of articles on immutability but still don\'t follow the concept very well.
I made a thread on here recently which mentioned immutability, but as
Immutability is about values, and values are about facts. Something has value if is unchangeable, because if something can be changed, then it means that no specific value can be connected to it. Object was initialized with state A and during program execution was mutated to state B and state C. It means that object doesn't represent single specific value but is only a container, abstraction on a place in the memory, nothing more. You can't have trust to such container, you can not believe that this container has the value you suppose should have.
Let's go to example - lets imagine that in code is created instance of Book class.
Book bookPotter = new Book();
bookPotter.setAuthor('J.K Rowling');
bookPotter.setTitle('Harry Potter');
This instance has some fields set like author and title. Everything is ok, but in some part of the code again setters are used.
Book bookLor = bookPotter; // only reference pass
bookLor.setAuthor('J.R.R Tolkien');
bookLor.setTitle('Lords of The Rings');
Don't be cheated by different variable name, really it is the same instance. The code is using setters on the same instance again. It means that bookPotter was never really the Harry Potter book, bookPotter is only pointer to the place where unknown book is located. That said, it looks like it is more a shelf then the book. What trust you can have to such object? It is Harry Potter book or LoR book or neither?
Mutable instance of a class is only a pointer to an unknown state with the class characteristics.
How then avoid mutation? It is quite easy in rules:
These few rules will allow to have more predictable and more reliable objects. Back to our example and book following above rules:
Book bookPotter = new Book('J.K Rowling', 'Harry Potter');
Book bookLor = new Book('J.R.R Tolkien', 'Lord of The Rings');
Everything is set during constructing phase, in this case constructor, but for bigger structures it can be a builder. No setters exist in objects, book can not mutate to different one. In such case bookPotter represents value of Harry Potter book and you can be sure that this is unchangeable fact.
If you are interested in wider scope of immutability, in this medium article is more about the subject in relation to JavaScript - https://medium.com/@macsikora/the-state-of-immutability-169d2cd11310.