Records in Java (JEP 359, preview)

Records in Java look very promising to me and a great addition to the language. The ceremony of creating pure data holder classes will be well know to any Java developer.

Sometimes we just create a class to transport some data from A to B. Most of the times we don’t even care about object equality or an efficient hash code algorithm. Nonetheless, the amount of code you (usually) generate is quite a bit. I’d go so far to say that the need to create classes for everything sometimes takes me out of the flow.

Take this simple example:

public class Person {
  private String name;
  private String firstname;
  private String address;
 
  public Person(String name, String firstname, String address) {
    this.name = name;
    this.firstname = firstname;
    this.address = address;
  }

  public String getName() {
    return this.name;
  }
  
  public void setName(String name) {
    this.name = name;
  }

  // ... all the other getters and setters, hashCode() and equals(), toString()

With records we would be able to declare a pure data holder structure way easier. And the best thing: it takes care about equality, hash code generation and a proper string representation (toString())

record Person(String name, String firstname, String address) {};
Image result for meme unbelievable

Yep, that one line expresses the same thing as the class above.

As a seasoned Java developer you may know that you can declare a class locally as part of a method. I don’t think this is common practice, but with records I could imagine that we can solve several problems in a very elegant way by just declaring a local record.

Try it out today

You can download early access builds from https://jdk.java.net/14/ (just unzip it somewhere you find it again). No comfort version, without any IDE – it’s fun to use these commands from time to time. Just keep in mind to enable the preview features:

Compile

c:\Dev\jdk-14\bin\javac -source 14 –enable-preview YourClass.java

Run

c:\Dev\jdk-14\bin\java –enable-preview YourClass

Personal opinion

I like it. But I feel like I’m saying this for every new Java feature. I do have some concerns about pattern matching and switch expressions as you can read in my other posts. But I don’t see a lot of trouble with this one coming!

Leave a comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.