DEV Community

Discussion on: What Do You Think About Immutable Data?

Collapse
 
tiguchi profile image
Thomas Werner • Edited

I ran into situations where mutable data structures were biting back. For example, I wrote an event bus subscriber and I was holding on to an event data structure my subscriber received. Strange things happened down the line, since the event object was actually mutable and internally reused by the sender for performance reasons. The unexpected changes of the event data caused erratic behavior. That was a bit of a head scratcher and took me some digging in 3rd party library source code to figure out.

I guess doing something like that makes sense in Java land in order to avoid heavy garbage collector activity, if a ton of events are published in quick succession. But it should be clearly documented :-D

Another example are "fluent builders" (builder objects that allow you to configure a result with chained configuration method calls). I really dislike builders that are internally mutable and update their internal state after each call. I prefer builders that return an immutable "stage" snapshot of the current configuration. I think that's more flexible if you want to preconfigure a builder with some common settings and use that same builder for various different purposes.

Yet another (Java) example for mutable objects that can break expectations are data structures that are used as map keys. If the same key object is modified after inserting into a map data structure in a way so equals and hashcode produce different results then that could cause some unpredictable outcomes depending on the map implementation. Probably in best case a crash. In worst case map data corruption / loss.

Personally I try to make my data structures compact and immutable if possible to prevent weird things from happening :-)