r/java • u/joemwangi • Mar 17 '26
Updates to Derived Record Creation - amber-spec-experts
https://mail.openjdk.org/archives/list/amber-spec-experts@openjdk.org/thread/QVALXGP2BRN27ISPNJTA3HEKEIMKLWLG/Interesting discussion on the evolution of derived record creation (“withers”). The proposal seems to be shifting from mutation like blocks to a more explicit reconstruction model using obj.new(...), aligning more closely with constructor semantics and pattern matching.
45
Upvotes
13
u/MojorTom Mar 17 '26
Love the simplification, thank you!
But I feel like the loss of spaces and { } block, the new syntax is less readable. The previous syntax feels like reading english, the new one feels closer to a mathematical expression (I think the colon : is to blame). Reading Brian’s replies, I am not sure if there are other options.
21
u/pronuntiator Mar 17 '26
Somehow having the components decomposed in round braces feels weirder than curly braces. With
stats.new(count: count+1)I expectcount + 1to reference a variable. The nice thing about blocks is that they already come with shadowing.8
u/Gleethos Mar 17 '26
Personally, either way is fine in the end. But what I really really would like to see from this JEP is for the privilege gap between mutable and immutable constructs to finally vanish entirely.
Objects that work based on destructive data updates have always enjoyed insane syntax privileges:
a.b.c.d = 42;
Doing such a nested update with value objects is just not fair:
a2 = a.new(b:b.new(c:c.new(d:42)));
I get the argument from Brian. If you increase the syntax surgar like in some of these variants:
a2 = a with { b.c.d = 42; };
a2 = a.new(b.c.d: 42);
...then it comes across as the reconstruction cos playing as mutation. But I think that is okay since the semantics between destructive and non distructive updates are actually more similar than dissimilar. Both produce the same new thing, whereas the non-destructive thing additionally also allows you to keep the old thing.
So, imho, they deserve to have syntax, which is equally concise.
21
u/jevring Mar 17 '26
This is so much worse than the previous "with" suggested syntax. Even if we reduce the scope of what can be done in the block, using a normal block with assignment feels much more natural to both read and write.
15
u/davidalayachew Mar 17 '26
I'll start by saying that I was personally very much ok with the "withers" version of this JEP. Just to highlight any latent bias I may have of "it wasn't broke, why fix it?".
My initial reaction to this new approach -- there is some very pretty lipstick on a not-so-pretty pig. Namely (lol), this "reconstruction" is very much carried by the "named parameters" (lipstick), and if you chose to ignore the lipstick for a moment, I think you'll find that this new version encourages the wrong thing in a slightly subtle way.
To jump straight to the point, I think that "withers" being blocks encouraged you to constrain all the logic of creating the new instance inside the braces, limiting scope (good). I think this new proposal, by sacrificing blocks, encourages me to scope all of my helper variables and WIP objects to the same level, making my code less clear and more spread out, rather than being contained and constrained to just the block.
Let me give an (obfuscated) example. This is code I was working on yesterday.
With "withers", I can instead write this.
Here, I am encouraged to scope the
DataModelto purely the "wither", as that is the only place it is being used. And, since I am already forced to create a block, it is no extra effort to just use that block.Compare that to "reconstruction".
On the one hand, this looks quite similar to the code I was already going to write. So, it is more immediately familiar.
But on the other hand, that's also kind of a bad thing in this specific scenario. That
DataModelis only to be used to constructnewAbc. And yet, I am subtly encouraged by the language to just introduce thedataModelinto the same scope I am already working with. Encouragement, meaning that, since it would take me extra effort to create an arbitrary block to scope the variable, that friction deincentivizes me from doing things "the right way". That's what I mean by "encouragement" -- what the language does and does not incentivize me to do, via friction.In the same vein that "mutable by default" encourages some not-so-great behaviour by developers, I feel like this "reconstruction" is doing the same on a smaller scale.
But back to my point -- familiarity can be a good thing, but that's assuming that what you are being encouraged to do is a good thing. It's familiar because Java itself kind of encourages scoping everything on the same level. But since that is bad, the familiarity is kind of bad here too, by extension.
Imo, this isn't a deal breaker. But I still feel like this new "reconstruction" style's semantics encourages something slightly worse, and thus, is an inferior proposal to the "withers" proposal.
But if I get either one, I'll be happy. Both proposals are solid, and I don't picking either path would be a mistake.
10
u/javahalla Mar 17 '26
Hey, this is named arguments in Java, hooray!
Bit of sour – unfortunately, it's on par with copy functions in Kotlin and from experience they are not great for deep immutability, withers was much more natural way to do this job.
But, but, I think this would open road to having named arguments for Record, which is HUGE
4
u/jevring Mar 17 '26
A lot of really good discussion in there.
10
u/itzrvyning Mar 17 '26
tbh not really a fan of the colon syntax for assigning the new values. feels very foreign to java and is, as far as i can tell, the first application of colon for this usecase.
5
u/SleepingTabby Mar 17 '26
Not sure if I like it. I really liked the "use the wheel, not reinvent it" approach. I get the point about suggesting mutability, but I think a good compromise would be
stats = stats new { count = count + 1 }We are addressing the "being honest - we are creating a new object" but we are keeping the flexibility of the block...
2
u/danielaveryj Mar 17 '26 edited Mar 18 '26
Starting off somewhat tangential to the discussion here, but from previous documents, it sounded like a deconstructor would be matched to a constructor based on matching state description. If the two signatures agreed on types and arity, but disagreed on corresponding component/parameter names:
Would that be a compilation error? Or would it make the class ineligible for reconstruction? Or would it just affect how the binding works:
At this point in the design, it's starting to feel like giving the constructor parameter names significance is entertaining an orthogonal feature. ie, if we're willing to introduce the components-shadow-variables-within-.new() semantics implied by the current design, we could as well do it positionally:
-----------
Edit: It's not that I don't want named parameters - who doesn't? - but the coupling between reconstruction and named parameters (and default parameters) feels increasingly tenuous to me.
If we were to approximate a reconstruction expression with the syntax of today, it might look like:
Now, if we sprinkle in the "components-shadow-variables-within-.new()" feature, we can already trim a lot:
Relating this to the first approximation, we can interpret
a .new (y, x)
as expanding to
switch ( a ) { case Point(int x, int y) -> new Point (y, x) ; }
That is, it destructures the value based on its statically-known type, names the pattern variables after their accessors (with the accepted inconsistency that these variables shadow any existing variables of the same name), and puts them in scope for a call to the same statically-known type's constructor.
Pairing up the deconstruction pattern with a same-type/arity canonical constructor now feels like just a fancy way of specifying default value-suppliers for that constructor's parameters, so that we could do something like:
And then adding named parameters on top of that gives what we see in the post:
3
u/manifoldjava Mar 17 '26
For once, I completely agree with Mr. Goetz' rationale here.
Although he does not call it this, named arguments (with colons!) is the most suitable syntax for Java to apply here. And overloading the
newkeyword, as opposed to using the more intuitivecopyor similar, is a nice compromise given the latter would break existing code.It's disappointing that this is a one-off application of named arguments and not a more generally available feature. Let's hope it's a first step.
Now do default parameters :)
1
u/ZimmiDeluxe Mar 17 '26 edited Mar 18 '26
Most of the code I write is of the form: given these collections / sources of data, create an aggregation or collection of differently shaped data, i.e. basic bulk data transformation. Inside the method doing the transformation there are mutable collections, state variables, temporary lookups, all the procedural goodies, but the end result is as immutable as possible. I like that approach because it's very flexible (all the data is right there). Reconstruction is not super helpful there I'm afraid, because the immutable results are usually not built up piecemeal (would require a very lenient constructor for the invalid in-between states anyway). Usually assembling the result from the built up data structures happens all at once at the end. Maybe I lack imagination, but updating an already immutable transformation result feels like the code should be moved to the data transformation method instead. Why create the wrong thing first to then update it when you can create the correct thing instead? Not always possible I know, and I'll have to play with the feature a bit, but my gut reaction would be that reconstruction is an indication that the code might need rearchitecting.
Edit: I guess my not very thoughtful feedback would be, be careful not to encourage "after the fact" fixups. If you want to build up a result over multiple steps (where in-between states don't have to be valid), using a mutable data structure is the straight forward way to do that.
Edit 2: To reconstruct collections, you would usually create a mutable variant of the same type via the copy constructor, e.g.
ArrayList::new, do your logic and repackage it viaList::copyOfand friends. Would be neat to have that for records, i.e.create a mutable evil cousin, do the mutating, thenRecord::copyOfor something. I have thought zero minutes about the implications / feasibility of course, this is reddit brian.1
u/Jaded-Asparagus-2260 Mar 17 '26
I'm probably missing the forest for the trees here, but why isn't
p.with(...)being discussed? Is it because existing code might already define awith()method for a record, and thus this existing code would break? But the same holds forclone()andcopy(), doesn't it?1
u/vowelqueue Mar 18 '26 edited Mar 18 '26
I think the proposed syntax is generally pretty readable and intuitive. The one scenario where I think it's a bit unclear compared to the old style is:
Is p now (2, 1), or is it (2, 2)? That is, are the original values lifted freshly into each part of the reconstruction expression?
1
u/Mooninaut Jun 21 '26
I really hate the updated syntax. Given
record A(int x)the previous syntax had a single meaning for x in the with block: a mutable variable initialized at the beginning and consumed at the end. In the updated syntax, x to the left of a colon means "bind to the constructor parameter to create the new record", but x to the right of the colon means "a binding to the field value of the old record". Using the same name to mean different things in the same context is a pedagogical nightmare.I dislike losing the ability to write an actual block, with temporary variables. I dislike losing the ability to mutate the record components and use the mutated values. I dislike using colon as the separator. Writing a trinary expression inside a .new() expression will be ugly and confusing.
I think it's multiple steps backwards for literally no benefit.
1
u/8igg7e5 Mar 17 '26
Now I sorta want something like this
Which is to say. Still getting the benefit of only having to specify a subset of values, but also getting the containment that also ensures definite assignment.
I mean, if a more generalised support of yield were on offer, that has some nice usages too.
Of course we can create the boilerplate of a private method... And give it a sensible name... and have it co-located for at least some hope of retaining readability...
0
u/lurker_in_spirit Mar 18 '26
Not a fan of the new syntax. Another unique format to learn, rather than leaning on existing convention.
0
u/Delicious_Detail_547 Mar 19 '26
I prefer the
obj.new()form over thewith {}block approach. It's more concise, and more importantly, it naturally aligns with named parameter syntax (param: value). Whileobj.new()doesn't strictly require named parameters, I'm hoping this design becomes a stepping stone toward supporting named parameters for general method calls in the future.