Main Content

Muttable v immutable and implications - Ruby

Archive - Originally posted on "The Horse's Mouth" - 2012-06-20 07:25:42 - Graham Ellis

A muttable object is one which can be changed in situ, and an immutable object is one that can't be changed in situ - if you want a modified version, you have to build it afresh, using whichever components you require from the orginal. And if the original's not required, you can then scrap it.

There's a tendency for heavily object oriented languages to use immutable obects for simple data types, and muttable ones for more complex types. Thus Python's strings are immutable and Python's dicts are muttable. And this makes sense from a language design viewpoint; the internal structure of a muttable object needs to be more complex than the internal structure of an immutable one, and it will be slower to handle. Thus a tradeoff between complexity and flexibility which goes one way with the simpler object structures, and the other way with more complex object structures.

Does this all matter to the programmer using the language? Yes, it does. On yesterday's Ruby course, we set up two obejects containing identical data, and we tested if they were euqal - using the equal? method which tests if they're one and the same object. With a simple object (an integer), Ruby uses an immutable object and we ended up with two names of the same immutable structure - that's efficiency for you. But when we set up two arrays containing idential (the same) objects, these were muttable, and different ... and we got the opposite result from equal?.

As long as you're aware ... this muttable v immutable, and how it effects the language you're using isn't a problem. But without the knowledge of what's what, you can end us with little surprises when you test for equallity. Equallity is not as simple a concept as it sounds. Just like in real life!

Sample source - Ruby:
Simple object - immutable
More complex object - muttable