‘Stupid’ Question 30: What do we mean by immutable and mutable in OO?
Oki, English is not my first language so I tend to look up English words a lot, just to make sure that I know what the word means. Immutable and mutable are words often used in OO programming, and I needed a good definition and examples as I was trying to explain this to a friend. Oki, the picture examples below are not perfect, but I couldn’t think of anything better. If you have a great example, please share! I’ll update the post and add new images :)
(This is NOT me) If you get a Tattoo that is finished (not a work in progress type) it is immutable, you can’t change the lines- once you add a line it is a new tattoo.
A drawing of a flower on the other hand is mutable, you can erease, change, add and so on.
Immutable: The state of the object cannot be changed after creation
Example: String , you can’t change it after it is created. It looks like you can, but what happens is that a new string is created.
Mutable: The state of the object can be changed after creation
Example: Stringbuilder , you can change this object after you have created it. You can append, remove, replace, or insert characters to the same object,- a new one isn’t created as with String.
Comments
immutable = unchangeable mutable = can change and i know cos i was just watching pluralsight videos :)
You might also be interested in looking at persistent data structures[1]. A tattoo is a good analogy for an immutable type but is also works well for persistent data structures. Any part of the tattoo that is drawn is immutable and cannot be changed but new tattoos can be built on top of it (eg. filling in the colour). The old tattoo, the outline, then exists both as a tattoo on it's own and as part of a newer, bigger tattoo. Maybe that analogy is a little shaky, the linked list example in the wikipedia article makes things much clearer. https://en.wikipedia.org/wiki/Persistent_data_structure
yes yes I know, arghhhh what a mistaka-to-maka . he he, Published that one to quickly ;) Thanks for the comments, changed it immediatly ;)
Nice evening reading that one, I'll read it later :) Thank you for the tip! And the analogy :)
u missed one? gasp, get out of town! I actually remember it because the guy had a huge pile of dough and a bunch of cookie cutters and was putting stuff on some sort of "heap" .... dunno sounds messy :)
nice way of presenting the concept...
So... we know the difference. But what makes knowing this difference powerful to us as a developer? Large immutable objects "may" be a potential source of performance issues if they have to change regularly, but with modern PCs being so powerful would we ever see an issue? Would we have more reason to worry about this in the server space where there may be many more instances to consider?
It also helps to think that the word stems from mutate/mutation. If the characters of X-men were " immutants", they would have a problem :)
Last modified on 2012-08-23