Mark As Completed Discussion

Immutability, When and Why Should It?

Immutable objects offer a number of advantages over their mutable counterparts. Let's explore some of the reasons why programmers might prefer immutability:

  • Readability: Since variables remain constant, code is easier to understand. Extensive commenting is no longer required.
  • Speed & Efficiency: We spoke earlier about the advantage of mutability in the short-run, however using immutability improves speed and efficiency in the long-run. While writing immutable code requires more effort, it is easier to manage and update. Have you ever heard the expression "short term pain, long term gain?" That is immutability in a nutshell.
  • Traceability: This is made easier because it is possible to identify how and where data changes in the code, as well as which parts of the application need to be reloaded with each change.
  • Safety & Validity: Once an immutable object's state is verified, its safety and validity are guaranteed because no background process can change it without the developer's knowledge.
  • Caching: The immutability of the values of immutable objects makes them ideal for caching and simplifies testing and debugging.

Now that we've established that, let's look at mutability and immutability in the context of a few differing programming languages.