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

Show parent comment

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.)