[External] : Re: Question about circular references

Ron Pressler ron.pressler at oracle.com
Tue Jul 4 14:50:08 UTC 2023



> On 4 Jul 2023, at 13:32, David Alayachew <davidalayachew at gmail.com> wrote:
> 
> 
> I actually have no issue going outside of records to do this. A final class with final public fields would meet my needs just as well. But neither that final class nor a record can get past this circular reference problem because Java does not allow a circular reference while maintaining immutability and direct reference.

You’re repeating the same thing of reaching for a feature designed not for your use case. Records are immutable, but not everything that’s immutable is a record. Similarly, final fields do describe immutable data in Java, but not everything that’s immutable can or should be final.

Final fields are a Java feature that guarantees some things about initialisation order and other initialisation-related guarantees, but you can, in this case, think of it as the feature you use when you need to ensure there are no cycles. So what you’re asking is, how do I use Java’s feature for excluding cycles to admit cycles? The answer is: you don’t.

A common OOP pattern is to have a mutable builder than then uses private access to create immutable objects (don’t expose mutating methods). They can still be simple data carriers, and if and when we have deconstruction patterns for non-record classes they can make use of pattern matching, too. 

The language supports this just fine. It just doesn’t support it with the feature designed for tuples, because what you want isn’t a tuple, and it doesn’t support it with a feature designed to enforce a particular initialisation behaviour when it’s not the behaviour you want. Yes, you can rely on the fact that final fields are tied to constructors and so do some clever initialisation in the constructor, but my general point is that you’re reaching for features that were designed for other uses.

— Ron


More information about the amber-dev mailing list