[LRUG] The advantage of immutability?

Tom Stuart tom at codon.com
Wed Sep 9 03:37:31 PDT 2015


On 9 Sep 2015, at 11:25, Jonathon Horsman <jonathon at arctickiwi.com> wrote:
> Can you shed some light on why an immutable object is an advantage for a web-based Ruby app?

One short answer is that immutable values eliminate a whole class of confusing bugs.

For example, when you pass an object into a method, what can happen to it? If it’s immutable then the answer is: nothing, you don’t need to worry about it. But if it’s mutable, then maybe that method makes some change to the object (perhaps accidentally!) that is going to make your life difficult later on. You see this sort of thing all over the place in Rails: methods that go to great lengths to duplicate their arguments so that they can mutate them without leaking side-effects back to the caller.

You’re right that it can sometimes require more programmer work to create new values instead of mutating existing ones, and in the naive case it can also take more time and memory to do things that way, but the trade-off is that your program becomes simpler to reason about and you’re less likely to introduce really sneaky bugs caused by shared mutable state.

Cheers,
-Tom


More information about the Chat mailing list