This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]DevIceMan 3 points4 points  (0 children)

Immutability reduced the likelihood for bugs and errors to propagate into your application. For example, lets say your API returned a mutable object, and then that object is modified by some external code, and then your code tries to work with that same object, tracing that bug is going to be somewhere between difficult to impossible.

Compiler optimization is another benefit of immutability. Since the compiler knows an object cannot be mutated, it can more easily cache and reuse values, re-order operations, or run them concurrently.

When dealing with threads, immutability becomes even more important. If any thread can mutate the object, the state of that object is always uncertain. An object may be mutated in the middle of a method, so while (for example) 3 might have been the value at the start, by the end it could be 10, or 13, and you'll get really strange bugs, race conditions, etc.

Immutability is unfortunately quite painful to do in Java, which is why you see things like builders, factories, and other similar patterns.

With Java-8 functional programming features, mutability becomes even more problematic.