this post was submitted on 12 Feb 2025
43 points (89.1% liked)

Programming

18193 readers
78 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 [email protected]



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
[–] [email protected] 7 points 1 day ago

So your writing a game. This game has what I'm going to call "entities" which are the dynamic NPCs and such objects. So these objects are most easily conceptualized as mutable things. Why mutable? Well they move around, change states depending on game events ect. If this object is immutable you'd have to tie the in world representation to a new object, constantly just because it moved slightly or something else. This object is mutable not just because it's easier to understand but there are even efficiency gains due to not needing to constantly create a new version just because it moved a little bit.

In contrast the object which holds the position data (in this case we'll have 3 doubles x, y, z) makes a lot of sense as an immutable object. This kind object is small making it cheap to replace (it's just 3 doubles, so 3*64 bits or a total of 24 bytes) and it's representing something that naturally makes sense as being immutable, it's a set of 3 numbers.

Now another comparison your typical dynamic array type container (this is your std::vector std::vec ArrayList and friends). These are mutable objects mainly due to efficiency (it's expensive to copy the contents when adding new values) yet they also are easier to conceptualize when mutable. It's an object containing a collection of stuff like a box, you can put things in, take stuff out but it's still the same box, just it's contents have changed. If these objects are immutable to put something into the box you must first create a brand new box, and create a copy of the old boxes contents, and then put your new item into the box. Every time. Sometimes this kind of thing makes sense but it's certainly not a common situation.

Some functional languages do have immutable data structures however in reality the compiler usually does some magic and ends up using a mutable type as it's simply so much more efficient.