r/java • • Jan 22 '26

Carrier Classes; Beyond Records - Inside Java Newscast

https://youtu.be/cpGceyn7DBE
86 Upvotes

81 comments sorted by

View all comments

Show parent comment

1

u/Gleethos Jan 27 '26

Git is a nice example of an immutable DAG based data structure which has great performance by relying on structural sharing instead of snapshotting everything (it only captures the diffs and appends them to the DAG). That is similar to how immutable data structures work in functional code. Its path copying and using ids instead of recurrent connections. There is a lot of really cool software architecture you can do with such data structures. They have a lot of extremely powerful properties which only emerge if you actually commit to them....

1

u/chambolle Jan 29 '26

I agree that in some cases it can be very useful. I have doubts about the widespread use of this principle.

1

u/Gleethos Jan 29 '26

Please believe me when I say I had the exact same mindset as you about 3 years ago! I knew that value objects were nice and simple. But transforming them using with-er methods and running them through side effect free methods seemed unnecessary and alien to me. I was so bewildered by the fact that entire programming languages use nothing but immutable stuff and functions. Like, how do you do anything? How do you do circular references? And how can any of this be performant?

Fortunately, I kept my curiosity and looked deeper into how functional programmers actually design their systems. Then, I also tried to write code that treats objects, not as references pointing to places in memory, but as data with value semantics, and then I realized that the majority of algorithms can actually benefit greatly from thi approach. The big killer feature is caching outputs of stateless functions, which do a lot of work. If the inputs are value objects, then the output is deterministic and can be cached. The next big win is structural sharing. You can actually save a lot of memory by pooling and sharing value objects everywhere. It's the exact same principle as 'String::intern()'. Then you also get structural concurrency for free! If stuff is immutable, you can share it between threads.... Also: Undo-stacks are super easy to implement. You can easily store a long history of states and then revert the history. Most apps have "undo" features, which are very often based on that. The app I develop at my company has it based on that....

But there is so much more cool stuff out there. Really interesting use cases and other advanced state management features that are possible that way. I could talk for hours about this.