Mutable Strings

    mutable - liable to change.

immutable - unchanging over time or unable to be changed.

Ok so we have the definitions.

We know exactly what the words mean but how do they apply to programming? Let us move on to two new definitions.

    mutable object - an object that is liable to change.

immutable object - an object that is unchanging over time or unable to be changed.

We can directly use the original definition when we put it in terms of object oriented programming. The final question is how do I use this in practice?

    An immutable object must be initialized upon construction and rely only upon other immutable objects once initialized.


A mutable class is not immutable. You can change it, other people can change it, and you can't rely on it being the same. It could be changed in another thread, you can't even be sure of it being in the same state from line to line unless you have good locking. ( see: ValueObject )

The ability to alter the state of the object is the key concept, but the story doesn't end there. You might want to choose an immutable class in a threaded environment, because now you don't need to worry about locking, because nobody can write to it anyway.

You might want to choose immutable objects in a large system, because you can't be certain that nobody else has a handle on that input parameter and won't change it out from under you the first chance they get. You might want to choose immutable objects because they make reasoning about the behaviour of your code in small units possible--as in, if everything about a function relies on immutable data, you can look at that function in isolation, guaranteed.

There are performance impacts, but it's not all one way. Immutable objects enable a lot of optimisations you just can't do on mutable data, like aggressively sharing memory (because hey, it can't change) or more aggressive inlining. Mutable data tends to get performance increases when you need to make a lot of changes to blocks of memory.

If you're interested in seeing somewhere where immutability really shines, take a look at the HaskellLanguage, which was designed from the ground up for immutability, enabling language-level support for things like laziness and a lot of optimisation.


http://programmers.stackexchange.com/questions/214167/understanding-the-difference-between-mutable-and-immutable


EditText of this page (last edited May 15, 2014) or FindPage with title or text search