The Author Online Book Forums are Moving

The Author Online Book Forums will soon redirect to Manning's liveBook and liveVideo. All book forum content will migrate to liveBook's discussion forum and all video forum content will migrate to liveVideo. Log in to liveBook or liveVideo with your Manning credentials to join the discussion!

Thank you for your engagement in the AoF over the years! We look forward to offering you a more enhanced forum experience.

IT Fachbereich (1) [Avatar] Offline
#1
Hi.
Is there a simpler example in order to understand immutability?
17-18 is is difficult to understand because there are only code snippets from a more complex program.
A question to the listing 1.8(page 1smilie:
Aren't we forced to generate a new step(monster.PerformStep()) each time we want to move the monster? If the monster wants to move 5 steps, what then?
do I have to create a new step(move) in the memory heap?
and when movedMonster is garbage collected our monster "returns" to its initial position?
Where is the advantage in the case of immutability over state change of the object?

Thanks and regards
Frischmilch (1) [Avatar] Offline
#2
Re: immutability
Hi,
Immutability just means, that you can't change the state of the value "object" once it is created. There are several advantages, but i think if you read further it will be explained deeper.
If you want to move the monster 5 steps, you can execute monster.PerformStep().PerformStep().PerformStep().PerformStep().PerformStep(). Or you can create a new methode (function) with one paramter x to execute x Steps, for example.
Why should movedMonster garbage collected? Because you don't use it anymore? Well.. then you don't need it. If you use that Object later, it won't be deleted. movedMonster ist a "deep" copy from monster, so if movedMonster gets garbage collected it will not change its state. Remember, it's immutable.
I hope it helps in any fashion.