this post was submitted on 12 Feb 2025
46 points (89.7% liked)

Programming

18364 readers
53 users here now

Welcome to the main community in programming.dev! Feel free to post anything relating to programming here!

Cross posting is strongly encouraged in the instance. If you feel your post or another person's post makes sense in another community cross post into it.

Hope you enjoy the instance!

Rules

Rules

  • Follow the programming.dev instance rules
  • Keep content related to programming in some way
  • If you're posting long videos try to add in some form of tldr for those who don't want to watch videos

Wormhole

Follow the wormhole through a path of communities !webdev@programming.dev



founded 2 years ago
MODERATORS
 

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

you are viewing a single comment's thread
view the rest of the comments
[–] FourPacketsOfPeanuts@lemmy.world 31 points 1 week ago (5 children)

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 5 points 1 week ago (4 children)

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).

[–] Kacarott@aussie.zone 7 points 1 week ago

This is close, but as someone already said, an index into a list just means you are mutating the list.

Your stable "identifier" needs to be a function, ie. a reused design pattern. Compared to the list, this would be an index function which gets an element from an arbitrary list, meaning you don't have to mutate your list anymore, you just build a new one which still works with your function.

This is why languages which avoid mutation and side effects are always (to my knowledge) functional languages.

load more comments (3 replies)
load more comments (3 replies)