r/java • • Jan 16 '20

Records Come to Java

https://blogs.oracle.com/javamagazine/records-come-to-java
204 Upvotes

93 comments sorted by

20

u/netcyrax Jan 16 '20

I look forward for this feature. Finally, some kind of built-in data classes.

16

u/valkon_gr Jan 17 '20 edited Jan 17 '20

I am still not used to that Java is being updated more frequently now. I love it.

11

u/lurker_in_spirit Jan 16 '20

Will records be usable as JPA entities?

15

u/kaperni Jan 16 '20

Records are immutable. So if you need to mutate data they are probably not that useful.

8

u/karstens_rage Jan 16 '20

For javax.persistence and javax.ws.rs it seems like construct and deconstruct are the operative terms not mutate. Seems like records would be super useful in these cases.

1

u/thogor Jan 17 '20

I don't know if they are, but why would you want them to? Most of the time your entities are domain concepts that would benefit from encapsulating them properly. Unless I'm missing something ofcourse.

1

u/Kango_V Mar 23 '20

Never pass you infrastructure entities out into your domain model!

1

u/thogor Mar 23 '20

Interesting take. Could you elaborate your approach a little? What does your domainmodel look like and how do they relate to the entities?

1

u/Kango_V Mar 23 '20

Our domain model is made up of pure java objets. No lombok, immutables, no jpa, no spring. These objects are passed to a Store object. The store is a domain construct for storing/retrieving domain objects. The store internally has 1 or more repositories injected into it. These are the infrastructure layer. The store deconstructs the domain objects, translating them into the format that the infrastructure needs. The infrastructure objects then persist.

The infrastructure layer could be JPA, JSON files, Lucene, Elastic Search etc. The domain will not change as that is modelled to your use cases for the application.

We do the same with the web model through a service API into the model. Our application is in the model only The application can be tested without the web/infrastructure layers.

Requires a little more coding/discipline, but the end result is very maintainable/testable code.

1

u/thogor Mar 23 '20

Even though it requires some additional code, I quite like your approach! Thanks for taking the time to explain it. How would you feel about entity classes if all the mapping definitions were outside of the class files? JPA doesn't really give us any nice options besides xml config, but let's pretend that there is a better alternative. Would you still recommend having separate domain and persistence classes?

1

u/Kango_V Mar 23 '20

Wait for Value Types. That might be better suited.

1

u/pmarschall Jan 16 '20

Of course not.

0

u/raze4daze Jan 17 '20

What? Of course they can be once implemented properly.

6

u/pmarschall Jan 17 '20

Maybe once JPA adds explicit support. At the current rate of Jakarta EE development that's likely somewhere in 2032. Maybe Hibernate DTO projection will work before that but that's vendor specific.

The current design of records is fundamentally at odds with JPA. The main issues are immutability and final-ness. What you have to realize is the runtime version of a JPA enttiy class is vastly different from the compile time version and often is a subclass that includes support for lazy loading and dirty tracking.

I am also not sure to what extent JPA relies on Java Beans.

At the current moment it is unclear to me whether records:

  • can have annotations

  • can implement an interface

If these won't be possible then JPA support is going to be very hard.

5

u/loicmathieu Jan 17 '20

Records can have annotations and interfaces.

But as you said, JPA creates a proxy in front of the classes and as Records are final you cannot do this.

So the current JPA implementation didn't play well with records, I hope they will find a way to workaround this some day ...

4

u/GuyWithLag Jan 17 '20

Records are not designed to be jpa entities, they are way too lightweight for that.

They are an intermediate stage to algebraic data types.

They are an intermediate stage to inline classes.

They are supposed to replace all the tuples/pairs in use, with named components.

And of course, they are in preview, so Stuff May Change...

2

u/pmarschall Jan 17 '20

Good, that matches my impression.

0

u/[deleted] Jan 16 '20

[deleted]

3

u/duheee Jan 16 '20

Can't it be overwritten (didn't read the article)?

7

u/lukaseder Jan 16 '20

I'll be damned. I thought it wasn't possible but this compiles in jshell:

jshell> record R(int i) { public boolean equals(Object o) { return
false; } }

jshell> new R(1).equals(new R(1))
$3 ==> false

5

u/krzyk Jan 16 '20

Yes, all methods in record can be overwritten, AFAIR also the getters

3

u/krzyk Jan 16 '20

Wouldn't the fact that records are immutable be more important than equals/hashcode?

19

u/daniu Jan 16 '20

So... record field accessors don't follow the getX() standard that many ubiquitous libraries and tools rely on (Spring and Jackson come to mind)? Nobody started using Java 11 until it was supported by those, I can't see the use of records being any different.

18

u/krzyk Jan 16 '20

Java 11 was supported on day 1 in Jackson and quite similar in Spring (maybe 1 - 2 weeks later for Spring).

And thank God they got rid of those getX()

26

u/cogman10 Jan 16 '20

It's a preview feature. Spring and Jackson will have time to pick it up. You can ask a class if it is a record. You won't see it heavily used until Java 15 (September) at the earliest.

3

u/krzyk Jan 16 '20

There will be for sure a second preview, so Java 16 at the earliest (unless they want a third preview).

6

u/eliasv Jan 17 '20

Relying on convention for serialization is flimsy anyway. I'm sure maintainers of such libraries will welcome a more reliable mechanism to enumerate members reflectively.

And the prevalance getters and setters in the Java ecosystem is an encapsulation-breaking blight and it would have been a terrible mistake to endorse them by baking the convention into a language feature. Records make the contract of a pure data aggregate more principled than shitty bean conventions, and I think it was wise not to couple the concepts together in any way.

9

u/commentsOnPizza Jan 16 '20

Yep, but being a language built-in will mean libraries will be updated to use it compared to third-party solutions which can be hit-or-miss in terms of library support. It will be a little bit of work, but it’ll be great long-term.

9

u/lukaseder Jan 16 '20

Good riddance!

3

u/duheee Jan 16 '20

Nobody started using Java 11 until it was supported by those,

You can still use records for your own algorithms. As far as I can see (from other people's posts) they're unusable as JPA entities so their use will be most definitely in other places. Maybe as DTOs between data systems or something. Protobuf may be able to use them.

1

u/nonconvergent Jan 17 '20

Lombok doesn't use the get/set (so you have to be gentle with builders and Jackson) and Scala and Kotlin don't use them on case and data classes, respectively.

Get/Set is really just an artifact at this point. Sometime troubleslme too, as those particular verbs collide in other use cases.

0

u/[deleted] Jan 16 '20

[deleted]

14

u/ZimmiDeluxe Jan 16 '20

Me too. The get-prefix is semi-useful to distinguish between methods on regular classes that just represent data and ones that actually do something, but with records that's superfluous because they are data. And it's often a lie anyway, I've seen enough get-methods that have side effects.

8

u/temculpaeu Jan 16 '20

yeah, I have seen way too many methods with the 'get' prefix for no reason

31

u/[deleted] Jan 16 '20

[removed] — view removed comment

11

u/daniu Jan 16 '20

I'm also very happy with the way Java is updated, but I don't understand this particular decision.

Just follow your own bean naming standard, and those libs would work out of the box.

-8

u/BlueGoliath Jan 16 '20 edited Jan 16 '20

As /u/pron98 has said in the past, JDK developers don't feel consistency is all that important and it shows.

Project Panama's Memory Access API doesn't have "get" in front of its getters(despite boolean checks being prefixed with "is"), var is used in documentation despite providing no benefit and when old documentation doesn't, and now this. It's getting pretty ridiculous.

Blame the people who keep screeching that Java is too ceremonious and demanding things be made more "concise".

By Java 25 they are going to add optional semi colons.

24

u/pron98 Jan 16 '20 edited Jan 16 '20

Did I say that? I don't think so, although I agree that there are things more important than consistency. Anyway, the new record method names are fully consistent with the naming standard for record methods and not consistent with things that are not record method names, and I'm not exactly sure what other thing they should be consistent with and why, especially as the feature's JEP states:

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.

3

u/BlueGoliath Jan 16 '20 edited Jan 16 '20

Did I say that? I don't think so.

I believe it was in regards to the topic of var and/or API documentation months ago.

Regardless, you're saying it again:

Anyway, the new record method names are fully consistent with the naming standard for record methods and not consistent with things that are not record method names.

Records don't exist in a vaccum. To argue this is disingenuous and I'd hope as a JDK developer you'd realize that.

BTW, it's OK to be frustrated that other people have different opinions from yours -- most of us are frustrated by that -- but constantly blaming that on some flaw on their part is counterproductive. Even if your opinion is reasonable, the opposite opinion can be at least as reasonable.

Was anything said really an opinion?

Getter methods in previous Java APIs were commonly prefixed with "get" and many APIs rely on that.

There are methods that still have the "is" prefix for boolean checks.

var is now used in documentation without providing any value or makes the documentation muddy. There was a highly upvoted comment to my article thread like half a year ago agreeing that this is a thing.

Many newer language "features" have had "concise"ness as a motivation for their introduction into the language. Often times the JEP pages cite people complaining that Java isn't concise and is ceremonious.

So i'd like to know what part of any of that(at the core) is subjective/opinionated.

7

u/DuncanIdahos5thClone Jan 16 '20

Not sure where you've been but "is" is common for Boolean and part of the old Javabean spec.

5

u/BlueGoliath Jan 16 '20

Not sure where you've been but "is" is common for Boolean and part of the old Javabean spec.

That's the point. They are keeping boolean check methods prefixed with "is" despite removing prefixes from all other methods in order to make it more "concise". The end result is an inconsistent mess both when compared to older Java APIs and even from within its own API.

1

u/DuncanIdahos5thClone Jan 16 '20

OK sorry. I thought you meant that there are APIs using get's for booleans.

7

u/AngusMcBurger Jan 16 '20

I think 'is' and 'get' are quite different. For fields/variables I include 'is' for booleans because their name often ends up ambiguous without. Eg open() sounds like an action, isOpen() makes it clear you're asking if it's open. Where as file() works just as well as getFile() but with less noise

3

u/BlueGoliath Jan 16 '20

"file" can be either a verb or a noun so it's still ambiguous.

3

u/pushupsam Jan 16 '20

This is so stupid. A method called 'file()' could do literally anything. The entire point of 'getFile()' -- just like isOpen() -- is that it is a query which doesn't mutate the object.

(The real problem -- that Java lacks properties and so there's no way to express the concept of a read-only method -- is ironically something that was rejected by the same braniacs that are removing get.)

3

u/pron98 Jan 16 '20 edited Jan 16 '20

Your statement that var does not provide a benefit for documentation is an opinion. If we take the claim that language features are motivated by conciseness (only or primarily) as an objective assessment, then, at least as far as records and var are concerned, it is just wrong.

-1

u/BlueGoliath Jan 16 '20

Your statements that var does not provide a benefit for documentation is an opinion.

Is it? If the specific documentation is inconsistent with other documentation & omitted important type information(which is important for documentation) then surely it can be objectively concluded that it provides no benefit.

3

u/pron98 Jan 16 '20

Brilliant. I wish I had thought of that.

8

u/lovett1991 Jan 16 '20

On one hand I kind of disagree about the 'get' keyword. I think moving away from it means the method signatures give a clear indication this is a domain object only. I started using immutables a while back and after a while it grew on me.

On the other I do agree about the 'is' keyword being added whilst 'get' isn't, it feels weird as a Java dev but I guess as an English speaker it isn't it if the realms of how you'd write something. For instance I would say 'his age is...' not 'his get age is' whereas I would say 'he is active' as opposed to 'he active'

0

u/[deleted] Jan 16 '20

[deleted]

2

u/rzwitserloot Jan 19 '20

No, 'good libraries' won't be updated. It's quite a high cost to have an API that has both, say, getName() as well as name(), with both methods returning the exact same thing (forevermore, docs and listings such as in auto-complete dialogs), and I'm sure plenty of libraries will opt not to pay this cost.

An alternative is to mark the getX() variant deprecated, but that is in many ways an even higher cost; that's a heck of a lot of shuffling about for all the users of that library for no particularly sane reason.

Note that getX itself vs. X is a mixed bag: neither is strictly superior to the other (getX has the considerable advantage that you can type 'get' and then hit your autocomplete shortcut to find all properties you can query. It's also longer and having to decide between whether a thing is a 'property accessor' and something that calculates is more art than science and that's problematic – as I said, advantages and disadvantages).

Given that it is a mixed bag, causing an earthquake in the java community by trying to make such a change is ill advised: You're just not going to convince enough of the community to arrive at that utopia where (almost) all code uses getless accessors, instead now we'll have a 50/50 mix. I'm not too happy about this.

-5

u/pushupsam Jan 16 '20

There's everything wrong with abandoning a bad spec if people have been faithfully following that spec for 20 years.

There's something deeply wrong with the process if people really think it's okay to tell people that have invested millions of dollars and thousands of hours in the Java platform that, you know what, all that code you wrote, all those tools and documentation and checkers, based on the getX/setX standard that we defined? We're going to break that now.

Stuff like this is exactly why I tell people not to invest in Java any more. The language has gone off the rails. Backwards compatibility -- which was perhaps Java's greatest strength -- and the geniuses at Oracle are now actively making breaking changes in every release. And the stuff that they're breaking backwards compatibility for? It's really fucking stupid stuff like 'var'.

The irony here is these attempts to update Java are just driving people away. I cannot recommend any new greenfield projects be done in Java and, frankly, I don't see any reason to advance existing projects to new JDK versions.

6

u/klez Jan 16 '20

I may be naive here, but why would adding features break compatibility? Don't like var or var breaks compatibility? Don't use it. Same with records. It's not like they're telling you not to use beans anymore.

-19

u/pushupsam Jan 16 '20

Of course 'var' breaks backwards compatibility. Every time you add a new keyword, all code that previously used that as an identifier is broken. How do you not see that?

As for avoiding new features -- sure, that's a great idea. And in fact this is why these guys have killed Java. There are now two Java platforms: Java8 and this brainfuckery. The vast majority of corporations are not going to upgrade to this backwards incompatible brainfuckery. This is going to have huge rollover effects as the entire community splits in two.

It's absolutely shocking that despite the repeated warnings these guys really have decided that backwards compatibility is no longer valuable. This puts the nail in Java's coffin because absolutely nobody is going to invest in a platform run by guys who think nothing of throwing 20 years worth of code, documentation and tooling out the window.

14

u/jonhanson Jan 16 '20 edited Mar 07 '25

chronophobia ephemeral lysergic metempsychosis peremptory quantifiable retributive zenith

-20

u/pushupsam Jan 16 '20
public static final class var {
}

This used to work. Now it doesn't. Because of stuff like this 'var' did break a lot of existing code for no good reason. And when it did, guess what happened? Do you think people dug into code that's been chugging along for 10+ years?

19

u/sonay Jan 16 '20

Dude, please gtfo. If you named a class 'var' you have bigger issues.

15

u/cl4es Jan 17 '20

Because of stuff like this 'var' did break a lot of existing code for no good reason.

[Citation needed]

2

u/Polygnom Jan 18 '20

Because of stuff like this 'var' did break a lot of existing code for no good reason.

If you have lots of classes called var, the issue is with your code, not with the change.

Part of the process was investigation of real-world code-bases to see how much of an impact var would have. it was found to be practically non-existent, because, you know, people simply don't tend to use var as class name or in other places where it would come in conflict. at least not many.

-8

u/forsubbingonly Jan 17 '20

I feel sorry for people who write in languages that even COULD spawn this dumb ass discussion. What a bunch of trash.

1

u/JB-from-ATL Jan 17 '20

They explicitly said these aren't JavaBeans because they aren't mutable.

4

u/[deleted] Jan 17 '20

So Scala case classes?

2

u/kiteboarderni Jan 16 '20

Damn, Ben rocking the white hair look

2

u/benevanstech Jan 17 '20

It's actually a really old photo. My hair is a lot, lot longer these days.

1

u/kiteboarderni Jan 17 '20

Looks great! Fantastic article, excited for the applications we can use it for.

1

u/benevanstech Jan 17 '20

Thank you. :)

I hope to have a real-world (albeit demo) app that I can open-source soon - watch this space.

Oh, and: https://twitter.com/kittylyst/status/1218092254566416384 (note: longer hair, but this pic is still ~3 years old!)

1

u/kiteboarderni Jan 17 '20

When are you back to the nyjavasig? Would love to see the talk.

1

u/benevanstech Jan 18 '20

I am trying to optimize my intercontinental travel this year - longer trips less often and using trains whenever possible in Europe. I do not have any plans to visit the East Coast at present, but let's see what happens - I miss my NY friends!

2

u/jvjupiter Jan 17 '20 edited Jan 17 '20

Will it be fluent? Something like:

var user = new User().id(1L).lastName("Doe").firstName("John");

2

u/dany74q Jan 17 '20

Nope, the compiler will generate a public ctor with all of the fields, and accessors for each field; No setters will be created as records are immutable.

1

u/jvjupiter Jan 17 '20

I see. Thank you.

1

u/jvjupiter Jan 17 '20

If no setters would be generated, then JAXB, JSON-B, JPA and frameworks or libraries like Jackson need to be updated to be able to support records. Correct?

1

u/rzwitserloot Jan 19 '20

I think they may be able to handle constructors, especially if festooned with a @ConstructorProperties annotation. If not.. yeah they have to be updated.

1

u/randgalt Jan 20 '20

FYI - I wrote a library that adds a fluent builder/copy companion to Records: https://github.com/Randgalt/record-builder

2

u/[deleted] Jan 18 '20

They're a nice feature particularly for lambdas and streams but I can see them being widely (ab)used in inappropriate contexts.

However it is pretty obnoxious that you must use (non-standard?) accessor methods for what are just final fields, all those() add up and reduce readability significantly. The example is also rather contrived.

3

u/xnendron Jan 17 '20

I would much rather see an official adoption of the functionality provided by Lombok. Records seem fine, but I think reducing boilerplate code in JavaBeans would be more useful to more people.

1

u/heliologue Jan 17 '20

Records are a great way to move the language forward, but I agree that I'd much rather see some syntactic sugar like auto-generated getters and setters that lets us work with "legacy" conventions with a lot less boilerplate.

1

u/[deleted] Jan 17 '20

So I assume Compact Constructors is optional?

Like it wouldnt work if you had declared the field ImmutableList (using copyOf) and constructor took List parameter.

1

u/krzyk Jan 17 '20

Yes, you can use normal constructor. Although I don't know if the thing you describe would work.

You should return what you feed, so changing the class type of a record component inside constructor might be a no-no, you need to test it.

1

u/nutrecht Jan 17 '20

Awesome change. My primary reason for 'needing' Lombok in my Java projects is that I can't stand constantly creating/updating all these getters and setters. Great to see we can get rid of it soon.

1

u/PandersAboutVaccines Jan 17 '20

To what extent are java and kotlin copying each other? Records are about as close to kotlin's data classes as you can get within the limits of java. Did java borrow from kotlin, or did kotlin copy things they knew were being considered for java?

BTW, I wish they could steal this syntax from kotlin:

var newOne = oldOne.copy(justThisProperty = "changed")

2

u/djavaman Jan 17 '20

This seems to me more a borrowing from Scala than Kotlin

1

u/rzwitserloot Jan 19 '20

The idea of automated getter and setter (and more) generation predates the invention of project lombok, and that is over 10 years old now, so.. no. This is all just fairly common sense.

-3

u/Bobby_Bonsaimind Jan 17 '20

I don't get it...so this is just syntactic sugar to get final classes? Are there any runtime benefits?

Also the TOC-scroll-speed is infuriating...for fucks sake, just jump to the item I want to see, I'm literally faster to scroll by hand than to use the TOC!

-11

u/corner-case Jan 17 '20

Very cool, but I'm surprised the article didn't mention Kotlin.

5

u/kaperni Jan 17 '20

It's a joke right?

4

u/sureshg Jan 17 '20

Kotlin didn't invent data class. Eg: Scala has case classes even before kotlin.

-10

u/Akthrawn17 Jan 17 '20

Oracle can't acknowledge that this is inplementing the "data" keyword

0

u/[deleted] Jan 16 '20

[deleted]

5

u/lovett1991 Jan 16 '20

Yup this feels more like immutables than Lombok.

2

u/rzwitserloot Jan 19 '20

@Value (a lombok annotation; the immutable variant of @Data) does all of this. And you can toss @Builder at it for more.

DISCLAIMER: I'm a core contributor to lombok.

1

u/CodesInTheDark Jan 19 '20

In a long run records will be more useful than lombok (e.g. they will support pattern matching): https://cr.openjdk.java.net/~briangoetz/amber/datum.html

3

u/rzwitserloot Jan 20 '20

If you can destructure, you can pattern match.

Without custom destructure, you cannot change records.

Once custom destructurers exist, Lombok can make them for you.

Then such classes also support pattern matching.

0

u/[deleted] Jan 16 '20

[deleted]

6

u/duheee Jan 16 '20

Well, records would make it trivial to achieve that. Easier than before at least.

0

u/[deleted] Jan 16 '20

[deleted]

14

u/elastic_psychiatrist Jan 16 '20

https://cr.openjdk.java.net/~briangoetz/amber/datum.html

See “why not just do tuples.” Extremely justified IMO once you think about it.

2

u/eliasv Jan 17 '20 edited Jan 17 '20

Instance patterns down the line might help bring you closer. You can probably just define the two return types as part of an instance pattern signature instead of defining a container type for them.

So rather than your:

(int intResult, String stringResult) = receiver.functionWithTwoValues(...);

It might look something like:

let receiver.patternWithTwoValues(int intResult, String stringResult);

Or for a partial pattern:

if (receiver.patternWithTwoValues(int intResult, String stringResult)) {
  // values bound here
}

No carrier type necessary!

But not much has been said about them yet so who knows. https://cr.openjdk.java.net/~briangoetz/amber/pattern-match.html

3

u/8igg7e5 Jan 17 '20

Agreed, but when they've delivered value types and fixed nesting rules it won't be as bad. Of course it still mean having to find names for things that shouldn't really need it.

I wonder if anonymous records would be a useful concept...

public record(int id, String label) doSomething(...) {
    ...
    return new record(i, name);
}

...

var result = doSomething(...);
display(result.label());

This is mostly compiler sugar for creating an anonymous record with with named members. The generated class would need a flag so that reflection knows that the tuple-name is generated.

This would play nicely with proposed de-structuring and pattern matching and avoid declaring a record that would dirty the namespace. Additionally it's better than tuples with unnamed elements - eg display(result.1)

The return-type syntax doesn't really work though since it's starting tokens are not discernible from a nested record declaration.