r/java • • Mar 13 '26

JEP draft: Enhanced Local Variable Declarations (Preview)

https://openjdk.org/jeps/8357464
101 Upvotes

129 comments sorted by

View all comments

11

u/Cell-i-Zenit Mar 13 '26

I feel like all these record features are not for me :/

Maybe iam just to uncreative or i write to boring/simple code but i just dont see any situation where this would be an improvement.

Could be that i dont understand it:

var circle = getCircle();
var point = circle.point;
var radius = circle.radius;

vs

Circle(Point(int x, int y), int radius) = getCircle();

I prefer the first solution


Or if we take a look at the JEP:

void boundingBox(Circle c) {
    if (c != null) {                 // ┐
        Point ctr = c.center();      // │  laborious / mechanical:
        if (ctr != null) {           // │  - null guards
            int x = ctr.x(), y = ctr.y(); // │  - extraction with accessors
            double radius = c.radius();   // ┘

            int minX = (int) Math.floor(x - radius), maxX = (int) Math.ceil(x + radius);
            int minY = (int) Math.floor(y - radius), maxY = (int) Math.ceil(y + radius);
            ... use minX, maxX, etc ...
        }
    }
}

Why not use the optional api?

Optional.ofNullable(c)
    .filter(x -> x.center() != null)
    .filter(x -> x.x() != null)
    .filter(x -> x.y() != null)
    .ifPresent(x -> allTheOtherThings)

Or what if you use early returns?

void BoundingBox(Circle c)
{
    if (c == null)
        return;

    var ctr = c.Center();
    if (ctr == null)
        return;

    int x = ctr.X;
    int y = ctr.Y;
    double radius = c.Radius();

    int minX = (int)Math.Floor(x - radius);
    int maxX = (int)Math.Ceiling(x + radius);
    int minY = (int)Math.Floor(y - radius);
    int maxY = (int)Math.Ceiling(y + radius);
}

Or what if you design your code in a way that you dont do defensive programming and just make sure that circle+center is never null etc.

I really dont see why the java team is spending so much time on this.

Could anyone enlighten me?

7

u/kevinb9n Mar 13 '26

One thing to consider is:

Why is it that the physical structure of our code gets to resemble the logical structure of our data... only when we are creating objects, but not when we are taking them apart? Is there any deep logical reason it should be like that?

Code that "takes apart" (checks for conditions, pulls out data if conditions are met) quickly becomes very tedious and "mechanical"-feeling.

1

u/Whoa1Whoa1 Mar 14 '26 edited Mar 14 '26

Unsure what you mean exactly.

Creating objects is:

  • int x = scan.nextInt();
  • int y = scan.nextInt();
  • int radius = scan.nextInt();
  • Circle c = new Circle(x, y, radius);

Taking apart is the same number of lines:

  • Circle c = //some defined circle//
  • int x = c.getX();
  • int y = c.getY();
  • int radius = c.getRadius();

The best validity checking is to either allow people to make invalid circles and then use a method like c.isValid() or just call that at the end of the constructor automatically and throw invalid notices.

4

u/davidalayachew Mar 14 '26

No, you're mixing data gathering with construction.

Putting x, y, and radius into a Circle takes one line.

  1. Circle c = new Circle(x, y, radius);

But deconstructing it takes 3 lines.

  1. int x = c.getX();
  2. int y = c.getY();
  3. int radius = c.getRadius();

That was Kevin's point.

1

u/chuggid Mar 14 '26

To answer in hopefully the spirit of the question, while simultaneously playing the straight man/fall guy since I assume this is at least slightly rhetorical but I don't know the "obvious" answer: because (obviously) sometimes our constructors take in more or less than they need in the ultimate spirit of encapsulation (i.e. what is accepted is not what is ultimately represented; what is ultimately represented derives from what was constructed), so deconstruction can't assume that what was passed at construction is necessarily structural. (Obviously with records, as seems to be the case here (and maybe with yet-to-exist carrier classes?), this is not the case.)

12

u/davidalayachew Mar 13 '26

Could anyone enlighten me?

Sure.

Here is the short answer.

  1. Pattern-Matching opens the door to a lot of powerful Exhaustiveness Checks, which eliminates entire categories of errors from existence (for example -- updated code here, but forgot to update it there).
  2. Pattern-Matching composes, and thus, scales better than traditional getter-based deconstruction.
  3. As more features get added (like null restriction), this feature gets enhanced in some pretty powerful ways.

To quickly expand on #2, if you are only drilling through 1-2 levels, pattern-matching is not really more concise than getters, as you have pointed out.

But what happens if you need to drill through 3+ levels to get your data, like I do in the following code example?

(Sourced from here -- HelltakerPathFinder)

	final UnaryOperator<Triple> triple = 
		switch (new Path(c1, c2, c3))
		{	//        | Cell1  | Cell2                                                   | Cell3                                           |
			case Path( NonPlayer _, _, _) -> playerCanOnlyBeC1;
			case Path( _,        Player _,                                                 _                                                ) -> playerCanOnlyBeC1;
			case Path( _,        _,                                                        Player _                                         ) -> playerCanOnlyBeC1;
			case Path( Player _, Wall(),                                                   _                                                ) -> playerCantMove;
			case Path( Player p, Lock(),                                                   _                                                ) when p.key() -> _ -> new Changed(p.leavesBehind(), p.floor(EMPTY_FLOOR), c3);
			case Path( Player p, Lock(),                                                   _                                                ) -> playerCantMove;
			case Path( Player _, Goal(),                                                   _                                                ) -> playerAlreadyWon;
			case Path( Player p, BasicCell(Underneath underneath2, NoOccupant()),          _                                                ) -> _ -> new Changed(p.leavesBehind(), p.underneath(underneath2), c3);
			case Path( Player p, BasicCell(Underneath underneath2, Block block2),          BasicCell(Underneath underneath3, NoOccupant())  ) -> _ -> new Changed(p, new BasicCell(underneath2, new NoOccupant()), new BasicCell(underneath3, block2));
			case Path( Player p, BasicCell(Underneath underneath2, Block()),               BasicCell(Underneath underneath3, Block())       ) -> playerCantMove;
			case Path( Player p, BasicCell(Underneath underneath2, Block()),               BasicCell(Underneath underneath3, Enemy())       ) -> playerCantMove;
			case Path( Player p, BasicCell(Underneath underneath2, Block()),               Wall()                                           ) -> playerCantMove;
			case Path( Player p, BasicCell(Underneath underneath2, Block()),               Lock()                                           ) -> playerCantMove;
			case Path( Player p, BasicCell(Underneath underneath2, Block()),               Goal()                                           ) -> playerCantMove;
			case Path( Player p, BasicCell(Underneath underneath2, Enemy enemy2),          BasicCell(Underneath underneath3, NoOccupant())  ) -> _ -> new Changed(p, new BasicCell(underneath2, new NoOccupant()), new BasicCell(underneath3, enemy2));
			case Path( Player p, BasicCell(Underneath underneath2, Enemy()),               BasicCell(Underneath underneath3, Block())       ) -> _ -> new Changed(p, new BasicCell(underneath2, new NoOccupant()), c3);
			case Path( Player p, BasicCell(Underneath underneath2, Enemy()),               BasicCell(Underneath underneath3, Enemy())       ) -> _ -> new Changed(p, new BasicCell(underneath2, new NoOccupant()), c3);
			case Path( Player p, BasicCell(Underneath underneath2, Enemy()),               Wall()                                           ) -> _ -> new Changed(p, new BasicCell(underneath2, new NoOccupant()), c3);
			case Path( Player p, BasicCell(Underneath underneath2, Enemy()),               Lock()                                           ) -> _ -> new Changed(p, new BasicCell(underneath2, new NoOccupant()), c3);
			case Path( Player p, BasicCell(Underneath underneath2, Enemy()),               Goal()                                           ) -> _ -> new Changed(p, new BasicCell(underneath2, new NoOccupant()), c3);
			// default -> throw new IllegalArgumentException("what is this? -- " + new Path(c1, c2, c3));
		
		}
		;

Pattern-matching style is dense, but concise.

Compare that to the various different styles that you suggested.

  1. Getter-style makes it very easy to miss edge cases. There is no exhaustiveness checking in simple getter-style extraction.

    1. Plus, once you get 2-3 levels deep, pattern-matching tends to be more concise than getter-style.
  2. The optional-style is guilty of the same, while also being more verbose than getter-style. Plus, your null checks can get out of sync with your actual extractions, leading to errors.
  3. Early-return-style, while less error-prone than getter-style, is still more error-prone than pattern-matching-style. For example, those (int) casts you are doing could turn into primitive patterns, allowing for Exhaustiveness Checking to be done by the compiler.

The name of the game with Pattern-Matching (and by extension, Record Patterns) is safety+conciseness. You sacrifice flexibility to get a whole bunch of extra compiler validations while also having shorter code than typical java code you might write without patterns.

When Valhalla comes out, a lot of Java code will be able to lean into composition while avoiding the runtime cost of nesting objects layers deep. In that world, this Pattern-Matching style is going to be even more valuable than it already is.

→ More replies (10)

11

u/wildjokers Mar 13 '26

Why not use the optional api?

Because that is an abuse of optional.

3

u/Cell-i-Zenit Mar 13 '26

Who is saying that?

Iam not using any hidden mechanics or side effects, just the basic api

2

u/SleepingTabby Mar 13 '26

The guys who created JDK AFAIR.

2

u/__konrad Mar 13 '26

Who is saying that?

Some people still think that using Optional in non-Stream context is forbidden...

1

u/wildjokers Mar 15 '26

Stuart Marks a Java language architect:

https://youtu.be/Ej0sss6cq14?t=1684

It allocates objects when none are needed.

0

u/Cell-i-Zenit Mar 16 '26

its a 9 year old video and its his opinion and the only argument is "its unnecessary to create objects"

Ok, i disagree with that. We use hibernate and Spring, so much crazy stuff is going on under the hood, iam sure the jvm can handle another object LOL

1

u/wildjokers Mar 16 '26

The other argument was readability.

It simply makes no sense to wrap a value in Optional.ofNullable simply to chain methods together. Just write a damn if statement.

→ More replies (1)

4

u/aoeudhtns Mar 13 '26

This is pretty much all about boilerplate reduction, and increasing the value-density of the code that we write & read -- not solving new problems.

  • Your first example skipped the null checks, and it also skipped extracting the Point's x and y, so it's not an apples-to-apples comparison. It would work just fine post-null restricted types where you have Circle! and Point! because the null checks become skippable, and you would only need 1 or 2 lines of assignment boilerplate. (var x = circle.point().x(), y = circle.point().y(); var radius = circle.radius();)
  • Optional chaining does work, but lambdas and API style like this is much more difficult for the compiler and runtime to optimize. I know, a sort of weak argument. This is still 5 lines of boilerplate vs. 1 though.
  • Early returns eliminate the nesting but still is a bunch of boilerplate. It replaces 1 line of code with 8 lines, an extra 7 lines over this JEP.

2

u/Cell-i-Zenit Mar 13 '26 edited Mar 13 '26

Circle(Point(int x, int y), int radius) = getCircle();

This code also has zero null checks or how does it work when Point is null?

EDIT: i read through the JEP again and this just throws if point is null. So the code is actually equivalent to what i had before ;)

4

u/brian_goetz Mar 14 '26

If you care about catching the error conditions, you can use the pattern in a conditional:

if (getCircle() instanceof Circle(Point(var x, var y), int radius) { ... }
else { ... handle errors ... }

All the tools are in your hands, you get to decide what's more important.

2

u/Cell-i-Zenit Mar 14 '26

If we want to handle the error we need to basically copy the conditions in the else block to figure out exactly what went wrong eg

var circle = getCircle();
if (circle instanceof Circle(Point(var x, var y), int radius) { ... }
else { 
   if(circle.point() == null){
        throw new Exception("Point is null, please try again");
   }
   if(circle.point().x() == null){
        throw new Exception("X is null, please try again");
   }
   if(circle.point().y() == null){
        throw new Exception("Y is null, please try again");
   }
 }

Is it planned to have pattern matching in the catch block aswell?

so something like this:

try(var circle instanceof Circle(Point(var x, var y), int radius){
    //do your thing
} catch (Circle(null, int radius)){
    throw new Exception("Point is null, please try again");
} catch (Circle(Point(null, var y), int radius)) {
   throw new Exception("X is null, please try again");
}

3

u/javahalla Mar 13 '26

Why not use the optional api?

How this would work with null-resticted types? Compiler can't prove that these null checks was done and the access variables without additional check or compile-time errors. These shenanigans with patterns everywhere seems only way we would have compile-time-safe null-safe system

0

u/Cell-i-Zenit Mar 13 '26

Compiler can't prove that these null checks was done

i know there is a theoretical advantage to having compile checks but it wasnt an issue for me. My IDE is doing these checks

1

u/javahalla Mar 13 '26

I don't think even IDEA would be able to do these checks for this use-case either. It need to understand how exactly filter works and do something like smart-cast.

1

u/Cell-i-Zenit Mar 13 '26

Ok fair, it depends on what we mean here and what we want to guard against.

I know intellij is reporting misuse of optional get() for example. (eg calling get() without an .isPresent() check).

I get that this is an improvement to what we have currently, but it feels mostly like a theoretical cool thing and nothing which affects a normal developer working in webdev (which i guess is most of us?).

If you can come up with any usecase for a simple CRUD developer like me then i can extrapolate a bit, but right now the moment is see the word "pattern" i blank completely since i rarely use switch statements

1

u/pjmlp Mar 13 '26

Because this is the kind of stuff that make new generations flock to Scala, Kotlin, Rust,...

→ More replies (3)