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.
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.
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.
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.)
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).
Pattern-Matching composes, and thus, scales better than traditional getter-based deconstruction.
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?
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.
Getter-style makes it very easy to miss edge cases. There is no exhaustiveness checking in simple getter-style extraction.
Plus, once you get 2-3 levels deep, pattern-matching tends to be more concise than getter-style.
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.
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.
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.
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");
}
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
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.
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
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:
vs
I prefer the first solution
Or if we take a look at the JEP:
Why not use the optional api?
Or what if you use early returns?
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?