r/programming • u/[deleted] • Jan 16 '20
Records Come to Java
https://blogs.oracle.com/javamagazine/records-come-to-java9
u/javajunkie314 Jan 17 '20
I think this will be a good feature. I also think it will take some playing with it it learn where the line is where one should switch from record to full class.
I will say, I'm kind of annoyed that they didn't stick to the getFoo() convention for the accessor methods, if only because there are reflection-based libraries out there that expect it — e.g. Jackson for JSON serialization. I assume in Jackson's case they'll have to add special support for records (if they haven't already).
14
u/eliasv Jan 17 '20 edited Jan 17 '20
Reflection based libraries can be updated. And once they are, having a reliable list of members and accessors reflected directly as part of the Class API will be way better than relying on convention. I expect libraries like Jackson will welcome this improvement rather than complain.
Plus, the prevalance of getters and setters in general is a blight on the Java ecosystem. Beans are encapsulation-destroying garbage in OOP. Records thankfully say that if you want a simple data carrier then you have to be principled about it and follow some basic rules.
1
u/Dragasss Jan 17 '20
Jackson and others already provide annotations to help them determine what to use and how. Shame that libraries even opt for some convention scanning rather than forcing you to use those annonations.
1
u/javajunkie314 Jan 17 '20
My preference is for a library that tried to do the right thing by default, and gives you configuration hold to change that. Jackson does that — it scans for the most common convention and then gives you a tremendous amount of flexibility to customize.
For records, though, there's no convention and there's no accessor method to annotate with
@JsonProperty("foo"). And I have to flexibility to make the library (JDK) emit the shape I may want — I'm now stuck choosing between the existing convention and this new convention.As I said in my reply to the comment above, I have no doubt that Jackson and many projects like it will update to look for record metadata using reflection. I'm just saying it sucks to throw out some two decades of convention.
1
u/javajunkie314 Jan 17 '20
I've heard the argument before that beans break encapsulation. I don't personally buy it. But I'm also not even talking about full JavaBeans style classes with getters and setters — my preference for years now has been to use immutable classes for data, with only getters and a factory method or builder. When I say I use
getFooconvention, that's what I'm envisioning.I do agree that many libraries will update to accommodate. Some of my concerns are:
Not all libraries will, especially not right away, since it's a preview feature. Some libraries will have to wait for a new version of the spec they implement. Some just won't because they're old and in maintenance mode, or need to keep building against JDK8 (or JDK6).
Whether my class is a record class or not must be part of my library's public API. It would be a breaking change to switch it after the fact. This is good in many ways, because it makes a strong semantic statement about my class to my API consumers, but it is something I have to commit to.
If I do try to change from a record to a full class, I will be forced to rename all my accessors to
getFoo-style if I still need to play nice with reflection-based libraries.I can't easily put the class behind an interface. Suppose I have an interface with a getter method. I can't use that interface for both records and non-records because they are forced to use different naming conventions. (I could get around this by creating a
getFoo()method on my record that delegates tofoo()but that's terrible.)I'm just worried it going to be like how we have both arrays and collections. They both do similar things but their APIs are completely incompatible. So we just wind up having to convert one to the other at code boundaries, and having two separate but similar sets of tools.
3
u/eliasv Jan 17 '20
I've heard the argument before that beans break encapsulation. I don't personally buy it.
Allowing anyone to come along and unilaterally, arbitratily modify and read your internal state is the exact opposite of encapsulation.
Not all libraries will, especially not right away, since it's a preview feature. Some libraries will have to wait for a new version of the spec they implement. Some just won't because they're old and in maintenance mode, or need to keep building against JDK8 (or JDK6).
I mean you're probably going to have to find replacements for libraries like that eventually anyway. I'm sure people made the same argument when generics were introduced. The only way to avoid that class of complaints is to just not evolve the language at all.
Whether my class is a record class or not must be part of my library's public API. It would be a breaking change to switch it after the fact. This is good in many ways, because it makes a strong semantic statement about my class to my API consumers, but it is something I have to commit to.
Sure that's a trade-off you'll have to consider. Just like choosing between a class and an interface, for example. That's just one of the things about designing an API, you have to pick the right abstractions to permit API evolution as best you can predict it, I don't see this as a huge extra burden on the design personally but I do see your point.
If I do try to change from a record to a full class, I will be forced to rename all my accessors to getFoo-style if I still need to play nice with reflection-based libraries.
Most libraries allow for using annotations rather than just method naming conventions right? I would never trust such a mechanism in the first place, sorry if you have to deal with such crappy reflection libraries.
I can't easily put the class behind an interface. Suppose I have an interface with a getter method. I can't use that interface for both records and non-records because they are forced to use different naming conventions. (I could get around this by creating a getFoo() method on my record that delegates to foo() but that's terrible.)
Someone working on a project which has adapted
fooinstead ofgetFooas their naming conventions would have the exact opposite opinion. That seems like just a matter of taste to me.I'm just worried it going to be like how we have both arrays and collections. They both do similar things but their APIs are completely incompatible. So we just wind up having to convert one to the other at code boundaries, and having two separate but similar sets of tools.
APIs should almost always use collections, and that will be even more true when we have generic specialization and e.g.
List<double>. But records are classes and the vast majority of APIs won't care about the difference, I don't see why there would be any conversions needing to take place at API boundaries except in extreme cases when interacting with reflection-based libraries, as we've already talked about.2
u/josefx Jan 17 '20
Allowing anyone to come along and unilaterally, arbitratily modify and read your internal state is the exact opposite of encapsulation.
You could enforce constraints in setters. Nor did you have to expose all your state with getters.
1
u/eliasv Jan 17 '20
Constraints aren't a solution, you're still allowing your state to be managed by someone else. You give up control of the behaviour which governs that state. Methods which modify state should contain descriptive verbs describing their behaviour, not just "set".
What if an operation needs to update many fields at once? Having to call many "sets" one at a time means for a period your object will be in an inconsistent state, and so per-field constraints can't help you.
And yes you can just not have getters, and that's my point, in most cases you shouldn't. State should not be exposed unless necessary. But if you are managing that state externally with setters ofc you will probably need getters of everything too...
10
u/_soundvibe Jan 17 '20
Jackson doesn't force you to use get convention methods. It works perfectly without them as well.
1
u/javajunkie314 Jan 17 '20
I may be forgetting because I'm not at my IDE, but I believe Jackson will only auto-detect getters that start with
getoris. You're definitely right that Jackson doesn't require such methods — you're free to annotate any method with@JsonProperty("foo")to include it. But records won't have visible accessors to annotate, so I think if Jackson's going to support records they need to get the list of accessors from the record's new reflection metadata.3
u/_soundvibe Jan 17 '20 edited Jan 17 '20
No need to have getters at all. You can just configure Jackson to use fields for serialization and constructor for deserialization without any annotations.
0
Jan 17 '20
[deleted]
2
u/javajunkie314 Jan 17 '20
I'm not saying using
getFooconvention is without it's own set of headaches. Just that not using that convention will also have headaches that I can see being real practical problems in my using this feature.
49
u/lunchlady55 Jan 17 '20
I can't wait til 2030 when cassettes come to Java and 2040 when compact disks come to Java.
5
u/gnus-migrate Jan 17 '20
It already has libraries that provide this functionality, they're just adding it into the language itself.
24
u/sabellito Jan 17 '20
Can you imagine the hype in 3020 when they remove nulls.
13
u/lunchlady55 Jan 17 '20
But think of the horror of that decade when everything starts failing with "NullNotFound" errors...
6
u/eliasv Jan 17 '20 edited Jan 17 '20
There are ways to provide non-nullability in a backwards compatible way. You have to mark uses of a type as non-nullable. But obviously it'd be ugly and shitty to have to explicitly mark all uses of a type with something that should be default, so instead they could mark it at the import location. IDEs would be expected to import non-null versions by default.
import java.lang.Whatever!; // ! makes non-nullable // uses of Whatever now are non-nullable. // uses of Whatever! are non-nullable (but redundant) // uses of Whatever? are nullable.That covers language support, and they have a type operator proposal which could support this at the JVM level.
Edit: added a little more to illustrate how this would work in conjunction with use-site decoration.
3
u/nutrecht Jan 17 '20
That won't work. THere's tons of places where you have Strings that can be null alongside the ones that can't.
It's rather unlikely Java will adopt a null-safe typesystem like ever. If you want that, you're better off with Kotlin.
3
u/pron98 Jan 17 '20 edited Jan 17 '20
It's rather unlikely Java will adopt a null-safe typesystem like ever. If you want that, you're better off with Kotlin.
Doing that in Java, in a backward-compatible way, is about as hard as doing it in Kotlin and C#, and easier than adding generics (especially after generics have already been added). I don't know if Java will ever do this and how (there is some data-gathering going on ATM), but Java has made bigger changes before. As always, it's a matter of cost/benefit of this feature by itself, and this feature compared to others. I agree it's probably not a good idea to do this per type, but you could say that in a particular Java file, all references are non-nullable by default.
1
u/eliasv Jan 17 '20
You would still have the use-site decoration option I mentioned as a backup. The import-site decoration was just suggested as a trick to allow people to "change the default behaviour" without breaking backwards compatibility.
So in one file:
import java.lang.Whatever!; // ! means non-nullable // uses of Whatever are non-nullable. // uses of Whatever? are nullable. // uses of Whatever! are non-nullable.And in another file:
import java.lang.Whatever?; // ? means nullable (same as default) // uses of Whatever are nullable. // uses of Whatever? are nullable. // uses of Whatever! are non-nullable.2
u/nutrecht Jan 17 '20
That means I have to go look at the imports to see if String is nullable or non-nullable in every source file. Sorry to be a negative nancy, but I'd hate this.
1
u/eliasv Jan 17 '20
Fine with me! I'm not proposing a language feature, I have no attachment to the idea and no horse in the race. Just pointing out that it is possible, and imo relatively straightforward so far as these things go. Yes there are downsides though!
0
14
u/BoyRobot777 Jan 17 '20
"Java does not have feature X, how the hell they don't have it yet?". Feature is shipped. "Haha it took them Y long to implement a feature". Misquoting song from Life of Brian - "Always look at the shit side of life".
-2
9
u/falconfetus8 Jan 17 '20
Your move, C#.
25
u/wllmsaccnt Jan 17 '20
Reified generics, advanced null handling, async/await, stack allocated arrays, tuple syntax, partial types, auto implemented getters and setters, dynamic types, extension methods, nullable value types, exception filters and many more...but sure, we'll give you this one as a first ;)
15
u/couscous_ Jan 17 '20
Type erased generics allowed Java (the JVM) to have better multi-language support (Clojure, Kotlin, Scala, and many more.). Scala wasn't able to get ported to the CLR because of reified generics. In either case, Java is getting a form of generics specialization for primitive types.
It also doesn't need async/await because it's getting green threads. I believe it has exception filters, just a different syntax than C#.
Let's not forget a best-in-class JIT and best-in-class GCs also.
0
Jan 17 '20
[deleted]
2
u/couscous_ Jan 17 '20
Both of those are intended to improve performance and C# typically has equal or better performance now than Java for most CPU bound tasks.
Citation needed. And the benchmarks game doesn't count.
5
u/igouy Jan 17 '20
And the benchmarks game doesn't count.
Because … ?
Because it's something they actually could reference ?
0
u/couscous_ Jan 18 '20
It's a good start don't get me wrong, but it's running on an outdated CPU. I ran some benchmarks myself where golang was quicker than Java in the benchmarks page, and I got the opposite result.
2
u/igouy Jan 18 '20
Specifically ?
(The details always matter.)
1
u/couscous_ Jan 18 '20 edited Jan 18 '20
I ran the spectral norm benchmark (input size 30000) with the following result:
golang:
1.274224153 18.81 real 70.19 user 0.38 sysJava (I think it was even version 3, which ran faster for me than version 2 which currently tops the benchmarks list for Java):
1.274224153 16.18 real 105.95 user 0.45 sysand nbody benchmark with input size 60000000:
golang:
-0.169075164 -0.169012474 6.09 real 6.04 user 0.02 sysJava:
-0.169075164 -0.169012474 6.04 real 5.94 user 0.06 sysI recall seeing a pull request submitted by someone for Java that uses
Math.fmawhich should have speeded up that benchmark (don't recall which one it is, but it's available in the project's list of issues), but because the CPU used to run the benchmarks didn't support it, it actually caused a degraded performance.The second issue with just relying on microbenchmarks to judge a platform is that they only test out specific parts of said platform, and do not highlight what it's capable of overall. For example, large Java programs do run faster than golang programs because of what the JIT is able to do (inlining, de-virtualization, certain cases of auto-vectorization, etc.), but microbenchmarks don't run long enough to be able to demonstrate this. Other long running Java programs work in high throughput rates (which the golang GC is bad at), again would be difficult to show in microbenchmarks.
2
u/igouy Jan 18 '20 edited Jan 19 '20
I got the opposite result
There's not much difference between the times for those Go and Java spectral-norm programs on the old machine —
spectralnorm.4.go 30000 121.462 elapsed secs spectralnorm.2.java 30000 120.786There's more difference between the times for those Go and Java n-body programs on the old machine, but still not much —
nbody.1.go 60000000 25.506 nbody.5.java 60000000 26.391Are you surprised that measuring program performance on different machines can give different relative measurements?
… Java that uses Math.fma which should have speeded up that benchmark…
Don't you think that use of FMA would also have speeded up programs written in other languages?
… only test out specific parts of said platform…
That's also true for complete apps.
Program performance measurements are brittle.
What you've said is not specific to the benchmarks game ("And the benchmarks game doesn't count").
… large Java programs do run faster than golang programs…
As you wrote: "Citation needed."
1
u/Tordek Jan 27 '20
Tangential, but there was a recent article about converting C to Rust, and the C version included some manual uses of vectorization and a hand-optimized inverse sqrt function, which the new Rust version elided. The Rust version was faster by a LOT because it used a native inverse sqrt not present in the CPU used in the benchmark game.
Source: http://cliffle.com/p/dangerust/6/ ~25% improvement
1
u/igouy Jan 27 '20
afaict there were a whole bunch of changes between
nbody-5.benchandnbody-6.benchnot justsqrt.If you're talking about this:
At face value, this should make the program twice as fast, because AVX instructions can chew on four f64s at a time instead of SSE's two. But, on my Skylake-based machine at least, the AVX version becomes slower.
:then afaict the faster program is the "outdated CPU" program that uses SSE ?
→ More replies (0)6
u/falconfetus8 Jan 17 '20
Hey now, I'm a C# fanatic myself. I just find it strange that C# has managed to add all of these great features, and yet somehow they're dragging their feet with records.
2
u/masklinn Jan 18 '20
You forgot structs (user-defined value types) which are a major feature missing from java when performance is a concern.
3
u/TarMil Jan 17 '20
C# has had pretty much exactly this as a design proposal for ages... I think it was first proposed for C# 6, now C# 8 is out and it's still just a proposal :/
2
u/falconfetus8 Jan 17 '20
That's just it: it's been a proposal. It hasn't shown any signs of actually being implemented any time soon. Java, on the other hand, looks like it's already decided on a design and is now going for it.
As a C# lover, I just want a damn record type already!
1
u/TarMil Jan 17 '20
Yes that wasn't a counterpoint, I was complaining with you :)
Even though I mostly use F#, I often enough interact with C# types that I would trust more with their immutability and comparability if they were declared as records.
1
3
u/jebailey Jan 17 '20
Wait. Compact constructors. When did that become a thing in Java?
8
u/Pandalicious Jan 17 '20
It looks like they're specifically for these new record types. More details about how they work here: https://openjdk.java.net/jeps/359
11
2
u/instanced_banana Jan 17 '20
That's one of the sexiest things I've found of Kotlin for POJOs. Glad it's coming to Java.
3
u/Nimelrian Jan 17 '20
Nice, turns out records are better at supporting DDD value objects than Kotlin's data classes due to leaving out the copy functionality
2
u/RichoDemus Jan 17 '20
I disagree, I would’ve liked to see copy
5
u/Nimelrian Jan 17 '20
It breaks DDD value objects though, because you can simply "copy" the object and provide invalid new values. I'd be happy if there were uncopyable and copyable records.
3
u/xtreak Jan 16 '20
HN : https://news.ycombinator.com/item?id=22068223. Python also has similar concept of dataclasses from Python 3.7 .
1
-7
u/ryuzaki49 Jan 17 '20
So, lombok.
14
u/sabellito Jan 17 '20
I used to love me some Lombok, however this is a stepping stone to get to ADTs and Pattern Matching in Java. Quite late to the party but better late than never.
5
u/ryuzaki49 Jan 17 '20
Absolutely. I made it sound like it was bad or whatever, but it's a really good idea.
-18
u/cr42yh17m4n Jan 17 '20
Java is trying to fight kotlin so hard.
6
u/nutrecht Jan 17 '20
There's nothing wrong, AT ALL, with different languages adopting good stuff from other languages. It's a net win for all of us.
13
u/BoyRobot777 Jan 17 '20
Kotlin stole it from Scala! /s
On more serious note, do you really think Kotlin has invented data classes?
-15
29
u/AngularBeginner Jan 17 '20
Will Java really get records before C#?