143 points · by agluszak · 6y ago · 159 comments
I was really surprised to learn that the Java compiler/VM, when it sees the patterns "somevar" and functions "getSomeVar" and "setSomeVar" doing purely getter/setter stuff, removes the actual function calls and silently changes them in the background to field lookups for speed.
If you attach a debugger or memory profiler, is changes them back to functions and slows them down. I'm not sure if this is still true; saw an example of this at a meetup back in the Java 8 days.
You seem to think that the goal is to get as many features as possible, as quickly as possible. Maybe some languages have that goal, but Java's design philosophy -- from its inception [1] -- has been to be a conservative language that only adopts features that have become familiar to programmers and stood the test of time in providing a good cost/benefit. Java hasn't always done this, but that's the aspiration. Worked out pretty well, I think.
Given Java's design philosophy, the far more interesting question is which features of those more adventurous languages Java does not intend to adopt.
> Java compiler/VM, when it sees the patterns "somevar" and functions "getSomeVar" and "setSomeVar" doing purely getter/setter stuff, removes the actual function calls and silently changes them in the background to field lookups for speed. If you attach a debugger or memory profiler, is changes them back to functions and slows them down.
It's true, and the optimizing JIT compiler does much more than just that. It performs deep speculative optimizations, like inlining virtual calls and removing untaken branches, reverting them (using a process called deoptimization) either for debugging or when it detects its assumptions are false. What you're referring to is just an instance of inlining.
[1]: https://www.win.tue.nl/~evink/education/avp/pdf/feel-of-java...
Worked out pretty well, I think.
Au contraire mon ami!ML was better than most of its successors, including Java, which held programming back. Milner's ML avoided some of Java's glaring mistakes (e.g. exception specifications, lack of generics, non-uniform treatment of types, lack of higher-order functions, lack of pattern matching) from the start. Xavier Leroy showed how efficiently to compile ML in the 1990s.
The main thing ML lacked (w.r.t sequential computing), was a good integration with OO and HKTs. That was solved by Scala.
As to the question of "holding programming back," it is yet to be seen how much of an impact these features have in practice. Same goes for what ML "lacked." I personally like some features more and some less, as do you, but I don't think anyone knows which programming language features really push programming forward.
[1]: https://cr.openjdk.java.net/~briangoetz/amber/pattern-match....
my new blog title
All the ones you named are fairly new languages, and C# does not have anything even remotely like records (structs are value types, and properties are fields) so what's your point? Java historically has been very conservative with implementing things because they usually try to get it right (generics non-withstanding). For that matter C# rushed into a few things too and screwed the pooch badly on them.
That said you are correct about records. Although it is getting them also.
How would you compare records to c# language features then? Are records value or ref types? Do they live in the stack or the heap?
They are data containers, not control structures.
Those are not directly analogous to records. As a matter of fact, C# is getting records as well: https://blog.cdemi.io/whats-coming-in-c-8-0-records/
In any case to answer GP, structs should not be considered a valid substitute for records, they are 'value types' so passing them around means you copy all the data every time you pass (i.e. lots of allocations if the record is larger than 1 or 2 fields)
Properties get you 'closer'. You can do some code Which is a good bit less than Java by default (i.e. not Lombok or similar)
F# does have Records, and technically there's nothing stopping you from declaring your records in F# and importing them into C#... but that may not be ideal. I don't think you get the full benefits (like copying a record with specific properties changed)
I think in Java’s case, its only mow getting struct-like semantics
edit I may be wrong. It could be a purely syntax level feature in Java as well.
Value semantics are proposed in JEP 169 [1] and are part of Project Valhalla. [2]
Debugging optimized code awkward as compilers will inline and eliminate many functions. I assume the debugger is being nice to you and undoing the optimizations to make things more intuitive.
In fact there was a point in time where polymorphic inlining was an active field of research and a number of people used the JVM to prototype their theories. Pretty sure a later version of Hotspot had polymorphic inlining as a feature.
The only truly problematic thing in the original Java design was type erasure, leading to mess in all JVM-based languages like Scala, Kotlin or Clojure, but it saved some memory, so it was a design compromise. C#/CLR chose the other option, making their VM more flexible.
!!!
Type-erasure of generics is what gives the other languages flexibility.
Scala eventually gave up C# precisely because CLR reification proved a huge challenge with Scala semantics.
You may not like JVM type-erasure but Scala would literally not be possible without it.
---
If anything, I would argue that Java should have done full type-erasure, not just type-erasure of generic types. (That does come with downsides though.)
In other words, Scala was designed on a hack involving JVM's type erasure, then authors found out the hack can't be ported to CLR. That's another way to view it. Type erasure is a half-baked mess in original Java, it was causing headaches right with the first version of generics...
What about Java's type erasure lets languages play better with variance strategies and data structures? It's not apparent to me that e.g. IronPython has a hard time sharing data structures with C# (although I haven't actually used IronPython FWIW). Why doesn't the usual strategy of upcast everything to `Collection<Object>` within a language where collections are covariant and then downcast as needed in a language that doesn't care about variance (e.g. a dynamic language) work?
Off topic, but I have been feeling nostalgic for Java, even though I now almost exclusively use Lisp languages and I am happy with that. In early Java years, Sun‘s main Java web site had a link to my site and I wrote a number of Java books. I was the number one search result for “Java consultant” for about a decade; Java was good for my career.
Which bug is easier to spot?
cat = new Cat(1, 2, 4);
cat = Cat.builder().eyes(1).legs(2).heads(4).build();
Additionally, from the examples in that post, records aren't valid JavaBeans either, so they can't be used with the myriad of existing tools/libraries that expect beans.From my first impression, it looks like records don't really address many of the reasons we use Lombok and its ilk, so many of us will just ignore this feature. Or do like I've done in the past couple of years, and just ignore Java altogether.
cat = new Cat(eyes=1, heads=2, legs=4);
Also, IDEs can help with parameter hints when is needed.
new Cat(eyes:1, heads:2, legs:4);I find myself often reading code outside of an IDE, such as in GitHub or other hosted repos. Why should it be less readable in those cases? Because it's marginally easier to write?
I also write a lot of Go code, and appreciate how "go vet" disallows unkeyed struct literals, forcing you to write the field names when creating structs. It is not an IDE feature, and I can freely browse GitHub or grep around in the command line and the code is just as readable as in an IDE. It also means Go works in a lot of editors and IDEs more easily, because those editors/IDEs don't need to implement a bunch of extra features to make the code actually readable.
I find it superbly powerful to be able to leverage the JVM and the Browser with the same language.
I used to have two customers who paid me to use Clojure on their projects, I liked Clojure (donated in the early days) but fast natively compiled tools like SBCL, etc. feel better to me. You have found a good home: Clojure and the JVM ecosystem is good for a wide range of uses.
Arguably, as Java already had Lombok for years, this does not add anything really new.
Apart from being a functional language one of main draws to Scala is the ease with which one can get rid of the boilerplate code. So kudos to the Java team!
Python has a number of these warts. Same with classes and type annotations.
And yes, there are codegen options (Autovalue, Lombok, etc.), but the build process is a little clunkier, and IDE support isn't great.
I would like to see:
new non canonical java.lang.BaseObject, which implements nothing.
new interfaces for .toString(), .equals( that ), and .hashCode().
Canonical java.lang.Object implement these new interfaces.
Any code wanting struct, data, record style objects would subclass BaseObject.
The JVM would auto generate missing .toString(), .equals( that ), and .hashCode() as needed. Like when you add a data class to a HashMap.
New syntax for properties, to eliminate need for setter/getter boilerplate.
New syntactic sugar for the static initializer constructor trick, to eliminate constructor boilerplate. Basically make new MyDataObject() {{ a = 1; b = "abc" }} look prettier.
--
Best as I can tell, only the last two would require language changes.
I for example, don’t immediately see any reason kotlin can’t use this to make a more efficient implementation of data classes.
It seems functionally identical at the VM/bytecode level to what Kotlin's data classes already do.
https://openjdk.java.net/jeps/169
This is disappointing.
Records, for example, are directly inspired by Kotlin's data classes, and function almost identically... except that Kotlin allows you to have mutable or immutable fields in a data class, and automatically provides a `copy` method (similar to Lombok's `wither`) that allows you to use a builder pattern.
This difference can be very important. For example, I don't see how a Record class could be used with most JPA-style ORMs, which immediately rules out Records for many of the most common use cases.
Why?
For one, mutation doesn't play well with pattern matching.
Sounds a lot like Scala case classes. More accurate to say that both Java records and Kotlin data classes are inspired by Scala case classes -- not that it matters, programming languages authors are constantly stealing ideas (sorry, drawing inspiration) from other languages; thereby moving the state of the art into the mainstream.
Oracle literally did the minimum effort required here, Java Records don't even generate bean-compliant getters FFS.
https://openjdk.java.net/jeps/359:
> Records provide a compact syntax for declaring classes which are transparent holders for shallowly immutable data... While it is superficially tempting to treat records as primarily being about boilerplate reduction, we instead choose a more semantic goal: modeling data as data. (If the semantics are right, the boilerplate will take care of itself.) It should be easy, clear, and concise to declare shallowly-immutable, well-behaved nominal data aggregates... It is not a goal to declare "war on boilerplate"; in particular, it is not a goal to address the problems of mutable classes using the JavaBean naming conventions.
That saidC I don’t even understand the point of generating getters in this case. The fields could just be declared public final. Java’s obsession with wrapping fields in methods has never made sense to me.
public record MktOrder(T currency, int amount)<T> { }
or public record MktOrder<T>(T currency, int amount) { }
Would be a bummer if it breaks the idiomatic (and canonical) way of working with generics. In any case, it's a much needed and welcome feature. public record MktOrder<T>(T currency, int amount) { }
var m1 = new MktOrder<USD>(usd, amount);This should be standardized by the language.
As someone not familiar with using those, can you ELI5 what those are and what their benefits are?
E.g. a method could return an unnamed tuple ("foo", 7) which might have type (String, int).
In some languages like ML, having tuples is such a fundamental part of the language that things like functions always act on a single argument which is actually just a tuple. So max(5, 5) is a function that takes a tuple of two ints as its parameter.
When you have tuples as a first-class concept, you can start to do some interesting shortcuts like:
(b, a) = (a, b); // swap two variables with no intermediate
or String (first, last) = name;
This is called deconstruction, where you extract a tuple into variables representing its members. This is common in a ton of languages (Typescript, C#, ML, Scala, Python, etc). It also forms a cornerstone of pattern matching expressions in some languages (Scala, Haskell) where you can create a condition and simultaneously assign the data you care about to variables that can then be used in that branch. Scala pseudocode: sum(list: ConsList<int>) {
return list match {
Empty(): 0;
Node(first, rest): first + sum(rest);
}
}That said, I also like Lombok's annotation style more, I can pick & filter which members are relevant for `toString()` and `equals()`
If the struct graph is all records or primitives, the compiler should include a toJson(), fromJson() in the sealed class.
It could be done with classes too, but if it was records/prims only, then it could be done without using reflection.
I'm looking forward to ditching lombok finally.
By which I mean those are the only LTS releases since the shift to frequent releases. The rest have been glorified betas, sometimes with major compiler bugs included (such as https://dzone.com/articles/jdk-91011-side-effects-from-on-ja... ). They have very little support and a super tiny maintenance window. I wouldn't expect any large or stable library/project to use anything but the LTS releases as a result. It looks like Java 17 is the next planned LTS release, which is quite a ways off.
I just roll my eyes at this point when I hear about it.
But today is not that day.
* June 2023 - Redhat [1]
* June 2023 - Corretto [2]
* September 2023 - AdoptOpenJDK [3]
[1] https://access.redhat.com/articles/1299013
[2] https://aws.amazon.com/corretto/faqs/
[3] https://adoptopenjdk.net/support.html private final double price;
private final LocalDateTime sentAt;
Can't help but notice that they won't be able to trade at exact decimal amounts whose fractions aren't sums of powers of 1/2.Also wouldn't Instant be better for a timestamp?
But for the purpose of the article, which is about Records being a new type of Java class, this is kind of irrelevant.
The FUD on money as a double is way overblown in my opinion - it only becomes a bad idea once you have to do precise math with the it (which is admittedly a lot of the time when you're dealing with money, but surprisingly rarely in some domains).
> This choice was partially driven by a key design idea in Java’s type system known as nominal typing, which is the idea that... each type has a name that should be meaningful to humans... the compiler still produced two different anonymous classes, $0 and $1...
Names extremely meaningful to humans!