It makes the code icky and hard to debug, and you can simply return new immutable objects for every state change.

EDIT: why not just create a new object and reassign variable to point to the new object

  • FourPacketsOfPeanuts@lemmy.world
    link
    fedilink
    arrow-up
    1
    ·
    17 days ago

    Simply put, because you often want to change the state of something without breaking all the references to it.

    Wild off the top of my head example: you’re simulating a football game. Everything is represented by objects which hold references to other objects that are relevant. The ball object is held by player object W, player object X is in collision with and holds a reference to player object Y, player Z is forming a plan to pass to player object X (and that plan object holds a reference to player object X) and so on.

    You want to be able to change the state of the ball object (its position say) without creating a new object, because that would invalidate how every other existing object relates to the ball.