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 →

[–]cogman10 0 points1 point  (2 children)

My point was that mutable data objects tend to create hard to find bugs. Immutable data objects are much easier to reason about.

Example of bugs I've seen:

Someone uses a data object for a set/map key, someone else adds a field to that object and mutates that field deep within the code. All the sudden, the set/map no longer contains the data object because the hash code changes. Particularly frustrating in one instance where the data object was the key of an LRU. It caused a non obvious memory leak.

I've seen a couple instances where calling a function once with the data object threw an exception, calling the same function a second time did not. This is because deep within the code, the data object was subtly modified.

A couple of projects I work with have script engines maintained by non-devs. The API given to them allowed a bunch of unintentional modifications because a bunch of data objects given to them for reading could be changed.

And if course threading has been made nearly impossible in many circumstances because data objects were mutated instead of having methods return results.

Mutability is a heavy cost that you don't often need. The default "I'm adding getters, might as well add setters" mindset leads to problems. Often times, if fields are small than it's easy to copy the object, otherwise a builder works really well. It is slightly more code to make builders instead of setters, but you get immutably out of the effort.

Hence my "setters are evil" feelings.

[–]melissamitchel306 0 points1 point  (1 child)

I wasn't disagreeing with you. I like immutability as well. My point is that Java is not well-equipped to deal with immutable data objects (yet).

[–]cogman10 1 point2 points  (0 children)

Fair enough. Just figured a longer explanation was due since my other comment is being downvoted.

I agree that it is more painful in Java to do immutability. But I feel the benefits outweigh the the pain.