Skip to main content
3 of 3
deleted 4 characters in body
David Arno
  • 39.6k
  • 9
  • 95
  • 129

The key to understanding why immutable objects are beneficial doesn't really lie in trying to find concrete examples in functional code. Since most functional code is written using functional languages, and most functional languages are immutable by default, the very nature of the paradigm is designed to avoid what you are looking for, from happening.

The key thing to ask is, what is that benefit of immutability? The answer is, it avoids complexity. Say we have two variables, x and y. Both start with the value of 1. y though doubles every 13 seconds. What will the value of each of them be in 20 days time? x will be 1. That's easy. It would take effort though to work out y as it's way more complex. What time of day in 20 days time? Do I have to take daylight saving into account? The complexity of y versus x is just so much more.

And this occurs in real code too. Every time you add a mutating value to the mix, that becomes another complex value for you to hold and calculate in your head, or on paper, when trying to write, read or debug the code. The more complexity, the greater the chance of you making a mistake and introducing a bug. The code is hard to write; hard to read; hard to debug: the code is hard to get right.

Mutability isn't bad though. A program with zero mutability can have no outcome, which is pretty useless. Even if the mutability is to write a result to screen, disk or whatever, it needs to be there. What is bad is needless complexity. One of the simplest ways to reduce complexity is to make things immutable by default and only make them mutable when needed, due to performance or functional reasons.

David Arno
  • 39.6k
  • 9
  • 95
  • 129