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
    2
    ·
    18 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.

    • Giooschi@lemmy.world
      link
      fedilink
      English
      arrow-up
      0
      ·
      18 days ago

      What you need here is not the stability in memory (i.e. of pointers, which you lose when you recreate an object) but instead just the stability of an identifier (e.g. the index into a list).

      • tunetardis@lemmy.ca
        link
        fedilink
        English
        arrow-up
        1
        ·
        18 days ago

        Well, but then you’re basically just pushing the mutability onto the container, since you need to be able to replace elements within it.

        It’s a good strategy at times though. Like say you’re working in a language where strings are immutable and you want a string you can change. You can wrap it in a list along the lines s=['foo'] and pass references to the list around instead. Then if you go s[0]='bar' at some point, all the references will now see ['bar'] instead.