Java Shot #6: Cut Down on Boilerplate with Java Records

One of the common complaints of Java is the amount of boilerplate code we have to write for a simple class to work.

Let's say we want to write a simple class which stores details of a Person, ideally, we just have to be concerned about the data variables and the functions of the Person class. But in Java, we have to write a lot more. What are those you ask?

  1. Constructors
  2. Getters
  3. Setters
  4. equals()
  5. hashCode()
You can use lombak to avoid writing these methods but what if you do not want to introduce an additional library into your application, what would you do?
In that case, you can use the IDEs to auto-generate these methods but there's a catch, and that is, adding a new data variables requires us to re-generate these methods, Imagine you forgot to update equals() and hashCode() method; It's a disaster waiting to happen.

To solve above mentioned problems, a special type of class is introduced in Java 14 called Record

An excellent explanation of this new class is provided on the Baeldung website. But here's the gist:

Person class using class keyword

public class Person {

    private final String name;
    private final String address;

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

    @Override
    public int hashCode() {
        return Objects.hash(name, address);
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj) {
            return true;
        } else if (!(obj instanceof Person)) {
            return false;
        } else {
            Person other = (Person) obj;
            return Objects.equals(name, other.name)
              && Objects.equals(address, other.address);
        }
    }

    @Override
    public String toString() {
        return "Person [name=" + name + ", address=" + address + "]";
    }

    // standard getters
}

Source: baeldung.com

Person class using record keyword

public record Person (String name, String address) {}

Source: baeldung.com

Using a Record is as simple as a single-line code. That's awesome, isn't it but there's a catch, read below!

🚧
Record generates final data members and hence setters will not be generated. Just remember record keyword when you need Immutability.

Key Usages of Record:

Consider using record for Requests and Responses in your controller and external calls. (Ensure that record is compatible with libraries that are used in your application like Jackson and then only use it in production)