r/java • • 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

82 comments sorted by

View all comments

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.

record ABC(A a, B b, C c) {...}

final OtherData otherData = ...;
final ABC abc = ...;

//this data model is only used in the creation of the newAbc
final DataModel dataModel = 
    Generator.generate(otherData, abc.a(), abc.c());

final ABC newAbc =
    new ABC(dataModel.versionA(), abc.b(), dataModel.versionC());

With "withers", I can instead write this.

record ABC(A a, B b, C c) {...}

final OtherData otherData = ...;
final ABC abc = ...;

final ABC newAbc =
    abc with
    {
        final DataModel dataModel = 
            Generator.generate(otherData, a, c);
        a = dataModel.versionA();
        c = dataModel.versionC();
    }
    ;

Here, I am encouraged to scope the DataModel to 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".

record ABC(A a, B b, C c) {...}

final OtherData otherData = ...;
final ABC abc = ...;

//this data model is only used in the creation of the newAbc
final DataModel dataModel = 
    Generator.generate(otherData, abc.a(), abc.c());

final ABC newAbc = abc.new(a: dataModel.versionA(), c: dataModel.versionC());

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 DataModel is only to be used to construct newAbc. And yet, I am subtly encouraged by the language to just introduce the dataModel into 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.

9

u/pron98 Mar 17 '26

Here, I am encouraged to scope the DataModel to purely the "wither"

It was never an attempt to encourage that, nor are we interested in actively encouraging scoping declarations to scopes smaller than a method. If you like doing things this way, fine, but that's not necessarily a better practice.

For somewhat similar reasons, we're not actively encouraging making local variables final. The point is that methods are small enough that you can tell at a glance (and the compiler can infer that, too) how declarations are used. Of course, you're welcome to introduce blocks or break up methods, but we're not interested in necessarily encouraging people to always put declarations in the tiniest sub-method scope; that's mostly a matter of personal taste.

1

u/OwnBreakfast1114 Mar 17 '26

As a follow up question, is there any research for what is worth encouraging that results in a better practice?

Independent of the research, is there any thing the jdk team is trying to encourage that would be nice to know about?

2

u/pron98 Mar 18 '26

Yes! For example, structured concurrency and record immutability. What's common to them is that they involve inter-method communication.

0

u/davidalayachew Mar 17 '26

but that's not necessarily a better practice.

[...]

that's mostly a matter of personal taste.

I contest that.

Why do we have local blocks at all, if not to accomplish exactly what I am doing? Where exactly the line is between "it's fine to be in the local scope" vs "it should be in its own scope" is different for everyone. But I still assert that there exists a breaking point where a scope is doing too much.

And sure, you can break it out into a method, but there is the exact same threshold for methods, where you can simply have too many methods in your class or it's various helper tasks. Furthermore, a method encourages reuse, which may or may not be relevant for the task on hand.

Hence why we have the ability to add arbitrary blocks, should we want to. There are sometimes where we just need a new scope, without the other features of a method.

So no, I assert that there are many situations where a local block is simply the clear, correct tool for the task at hand.

But back to the point -- because I believe that there are situations where developers should be encouraged by the language to use local blocks, I therefore believe that the "reconstruction" proposal is slightly inferior to the "withers" proposal, in that it does not facilitate it in a situation where I feel it really really should. Object construction is where it makes the most sense to have a local block.

4

u/pron98 Mar 18 '26

I contest that.

That's fine, and different developers have different preferences of what works best for them. But this is not generally recognised as a universal better practice, and so we don't view it as such. If that's how you prefer working - great. But we're not nudging everyone to use this particular style.

Unlike inter-method reasoning, even the mechanical compiler has full intra-method insight, i.e. everything going on in a method (e.g. the compiler knows whether a variable is assigned more than once; it doesn't only know that but makes use of that inference vis a vis lambda captures).

So I'm not telling you how to program, I'm just saying that not everyone agrees yours is the better way, and we're not (at least currently) interested in having the language prefer your chosen coding style.

-1

u/davidalayachew Mar 18 '26

But we're not nudging everyone to use this particular style.

[...]

and we're not (at least currently) interested in having the language prefer your chosen coding style.

If you are saying the idea of nudging everyone to use this particular style is not open for debate atm, that is fine. But my comment and previous response were to assert that you guys should do exactly that.

If it ever does become a subject for debate, lmk, as I have plenty more to add.

1

u/pron98 Mar 18 '26 edited Mar 18 '26

It's because this preference is subjective and not universal that we're not taking a stance. You're free to add blocks if you want them, and others are free not to. No one is saying that your style is wrong. The point is that developers do not agree on what is the "right" choice here, and because the stakes are low, it's not productive to even have a debate between the people who share your preferences and those who don't.

1

u/davidalayachew Mar 18 '26

because the stakes are low

Fair.

I disagree that the stakes are low, but agree that, comparatively, there are bigger things that deserve attention than this. For example, JEP draft: Null-Restricted and Nullable Types (Preview).

And thus, if the finite amount of attention that the OpenJDK team has to give will not be divvyed out to this issue (that I perceive to be extremely significant and something that affects all developers) in favor of something bigger like the null jep, then that's fine by me.

3

u/pron98 Mar 18 '26

And I'm saying that many developers disagree with you that your style is preferable to begin with. I have no doubt that you truly believe that your style is better, but it is often the case that even veteran developers strongly disagree about things, while both sides are vehemently convinced that theirs is the right way.

-1

u/davidalayachew Mar 18 '26

And I'm saying that many developers disagree with you that your style is preferable to begin with.

Obviously.

But there are many veteran developers that have built multiple Java applications, each generating revenue dollars measured in 9 digits, that think that Checked Exceptions are a mistake, and that you, Ron, should stop all work on Project Loom and Project Amber to go uproot Checked Exceptions from the language/turn them to Unchecked Exceptions. I can point to a single digit number of these people right now.

People disagreeing is not justification to not consider a feature. But, compounded with something like "low stakes" can be justification.

Hence why I highlighted your mention of low stakes. Because you are right -- this is lower stakes than other things, and therefore, compounded with the fact that there is disagreement on it, makes it not worth taking up the limited supply of oxygen atm. I can agree with that.

1

u/pron98 Mar 19 '26

There's a difference between disagreeing on relative priorities and disagreeing over the existence of a problem. Disagreement over priorities is usually a way of saying "I don't have this problem, but I recognise that others might".

We do recognise there's an issue with checked exceptions and have been playing around with ideas, but people may disagree on how high we should prioritise this. I don't think we've recognised a problem with method scopes being too big.

→ More replies

4

u/Eav___ Mar 18 '26

At this point introducing yield for normal code blocks is even more superior as it's generally usable, not only for reconstruction.

var display = ...;

var newDisplay = {
    var state = switch (display.state()) {
        case NotStart -> Running;
        case Running, Completed -> Completed;
    };
    yield display.new(state: state);
};

1

u/davidalayachew Mar 18 '26

At this point introducing yield for normal code blocks is even more superior as it's generally usable, not only for reconstruction.

I don't disagree.

That said, I spoke with Ron Pressler in another branch of this thread. Long story short, the risks I am pointing to are pretty low stakes compared to something like security fixes, or something universally agreed upon like the pain of NPE and null checks everywhere. So, my idea, plus yield for blocks, is on the back burner for now.

2

u/Ok-Bid7102 Mar 17 '26 edited Mar 17 '26

Why not just put that logic in a function?

If you want the ability to create variables, running arbitrary code, would you also want to be able to put anything in the wither block, for example for-loops, throws, try-with-resources, etc...?

What happens if the statements inside wither throw?
Does the language need new rules for that?
If one of the statements inside the previous wither block throws a checked exception how should Java compiler deal with that? Force you to deal with (catch) the exception in wither scope?

Arbitrary statements in the wither block open up a whole set of problems.

IMO the limited syntax is better because there's less "entropy".
I would see this feature as merely a helper to "update the relevant fields", and for other concerns we should use existing mechanisms.

2

u/davidalayachew Mar 17 '26

Why not just put that logic in a function?

Functions encourage reuse, relative the scope modifier you put on them. Sometimes I want that, but other times, I really don't.

That is why we have local blocks in the first place. Otherwise, we would simply just use methods anytime our scopes got too cluttered.

If you want the ability to create variables, running arbitrary code, would you also want to be able to put anything in the wither block, for example for-loops, throws, try-with-resources, etc...?

Absolutely.

For context, anything I would put into a constructor, I would want to put here. And I put all sorts of stuff into my constructors, including try-with-resources, catch blocks, throwing exceptions, for loops, and more.

What happens if the statements inside wither throw?

Does the language need new rules for that?

No new rules are needed. The underlying rules are exactly the same as if you had made a local block and added statements in there.

The only difference is that you are also adding the rules to include the "wither" functionality. But that doesn't step in the way of things like "what happens if you throw?". The answer to that question was already solved by the inclusion of local blocks, decades ago.

If one of the statements inside the previous wither block throws a checked exception how should Java compiler deal with that? Force you to deal with (catch) the exception in wither scope?

Arbitrary statements in the wither block open up a whole set of problems.

Are you familiar with the rules of local blocks in Java? If not, here are the rules in Java 26, according to the JLS -- https://docs.oracle.com/javase/specs/jls/se26/html/jls-14.html#jls-14.2

The snippet in question is this.

  • A block is executed by executing each of the local variable declaration statements and other statements in order from first to last (left to right). If all of these block statements complete normally, then the block completes normally. If any of these block statements complete abruptly for any reason, then the block completes abruptly for the same reason.*

IMO the limited syntax is better because there's less "entropy".

What makes you say entropy, specifically? I am not following.

I would see this feature as merely a helper to "update the relevant fields", and for other concerns we should use existing mechanisms.

This is a helpful comment, because it helps frame the rest of your comment in a new light for me.

I feel the complete opposite -- I see this feature as a new form of a constructor. A constructor has a block, and I feel like this should have a block too. A constructor can throw, have for loops, a try-with-resources, its own blocks, etc., and I feel like this should have those too.

2

u/Ok-Bid7102 Mar 18 '26

Ok, i think i understand the draw of with-er style. It's nice to get the most powerful language construct for this.

But let's think if there is something beyond syntax & coding style for this feature. If this feature was viewed completely in isolation i could agree that previous suggestion is better, at least only for being more capable (without going into syntax details).

But it could be viewed as the first piece of other potential future features. It makes this argument purely hypothetical as neither me or you can decide the future of Java, but let's try to imagine what else may be added to the language.

At it's very core this feature regardless of syntax and capability, will for the first time allow Java code to call a method (for now only the canonical constructor of records) nominally, but also omitting parameters.

So if you view this JEP as a special / early delivery of nominal & default arguments maybe it changes how the syntax should be.
Those hypothetical nominal parameters probably wouldn't go by syntax of foo(a = getA(), b = getB()) because that code means something even today, it assigns the a and b variables then passes them.
But the syntax foo(a: getA(), b: getB()) seems more plausible.

Why should this JEP be decided on a completely hypothetical future?
Given same capabilities, it's preferrable to have a lower complexity language.
It seems that complexity( feature "foo.new(a: getA())"; nominal arguments "foo(arg1, other: arg2)" ) is lower than complexity( feature "foo with { a = getA() }"; nominal arguments "foo(arg1, other: arg2)" ).

Does this change your opinion?
Because while ability to have code blocks inside with-er scope is nice, even without it the language isn't missing a feature / capability, you would just be doing it slightly differently. And if we ever got nominal parameters and this JEP chooses with-er style, then we would have 2 different syntaxes (meaning overall higher language complexity).

1

u/davidalayachew Mar 18 '26

So if you view this JEP as a special / early delivery of nominal & default arguments maybe it changes how the syntax should be.

I actually addressed this in my very first comment.

The named parameters is the lipstick, in my "Lipstick on a Pig" reference. I fully acknowledge that named parameters are desirable enough that they "boost" the value of this feature.

My point being, if the "lipstick" of this feature is the desirable part, then instead of putting lipstick on a pig, let's put lipstick on something more desirable instead. Meaning, focus on making "withers" a better fit for named parameters, rather than completely reworking it into "reconstruction".

1

u/Ok-Bid7102 Mar 18 '26 edited Mar 18 '26

By making withers a better fit for named parameters i guess you mean "make the syntax compatible / similar with what named parameters syntax might be".

If it was possible to have with-er with arbitrary statements and shared syntax with the hypothetical named parameters, then it's a question of do we really want a new code block / scope?

I think the added value of with-er over the simpler reconstruction is a bit dubious whether it's worth the complexity.

So you say you want the language to nudge you in the right direction, meaning put logic needed for the transforming the object (reconstructing it) inside its own block.
This is where it becomes subjective, even if we had the feature today, should you do some complex transformation inside the with-er block, inside an already complex method, or should name the transformation and put it in it's own method?

If there was a PR with a 200 line method and inside it a 30 line with-er block, wouldn't you want that with-er block to maybe be it's own method?
If it's 30 lines of logic that transformation is somewhat complex, why not name it, and maybe test separately?

So we again arrive at the first argument:

  • even if we have with-er blocks, it's not clear whether complex logic should simply be put inside the with-er block, or moved to a separate method.
  • if we don't have with-er blocks then simple transformations (compute any temporary variables) you would do within the existing method, and complex transformations (should) get placed in their own method

On a more abstract view: to some of us the smallest unit of logic is a function / method, it's the smallest unit with meaning / intention (described by its name, inputs and ouputs).
Code and statements are the smallest executable unit, but a single statement doesn't describe a meaningful action or transformation, and likely is useless to test on its own.
So if you ascribe to this view, the with-er block is unnecessary to group logic, functions already do that.

1

u/davidalayachew Mar 18 '26

If there was a PR with a 200 line method and inside it a 30 line with-er block, wouldn't you want that with-er block to maybe be it's own method?

I'd want it to have its own scope. One way to do that is by putting it into a new method. Another way is to put it into a new block. Each has its own tradeoffs and each has situations where it is the right choice.

If it's 30 lines of logic that transformation is somewhat complex, why not name it, and maybe test separately?

While testing is one reason why functions are the right choice in some instances, polluting the method space is one reason why they might not be the right choice.

If I have 10 different ways to construct the same object, and each is used in exactly 1 place, making a separate constructor for each is needlessly confusing and makes things more complex. Instead, it would be better to handle each situation individually and separately, locally. That's not always true, but I find it holds true in many cases.

And of course, I don't need to break logic out into a separate method to test it.

So we again arrive at the first argument:

  • even if we have with-er blocks, it's not clear whether complex logic should simply be put inside the with-er block, or moved to a separate method.
  • if we don't have with-er blocks then simple transformations (compute any temporary variables) you would do within the existing method, and complex transformations (should) get placed in their own method

Because I disagree with the previous quote, this quote's train of thought doesn't hold water for me.

On a more abstract view: to some of us the smallest unit of logic is a function / method, it's the smallest unit with meaning / intention (described by its name, inputs and ouputs).

Code and statements are the smallest executable unit, but a single statement doesn't describe a meaningful action or transformation, and likely is useless to test on its own.

So if you ascribe to this view, the with-er block is unnecessary to group logic, functions already do that.

I'm not really following your train of thought here, but I label my blocks all the time. I like to reference those labels for early returns, to simplify my logic. I am a firm believer in early returns for method/block design.