Introduction to Java records

The biggest criticism on Java is the large amount of boilerplate code it forces one to write. Python and newer languages like Kotlin seem to score over Java on this front..

Boilerplate code is not always bad. Sometimes verbose code is easy to understand and maintain especially if you are working with relative junior team members with a high churn rate.

However one case where boilerplate code is pure waste is when you have a java class with nothing more then half a dozen or more getter/setter. To make it worst, in a large project worth it’s salt you would be have dozens of classes like this.

Java Records a new feature in JDK 14 onwards comes to rescue. Each of the boilerplate data class described above now can be define in one single line. This is fantastic addition to Java and in our opinion will go down as a pathbreaking feature in history of Java.

Sample Java code without records public class Customer{ private String FirstName; private String LastName; private String Addr1; private String Addr2; private String City; public String getFirstName() { return this.FirstName; } public void setLastName(String lName) { } /*** getter setters for each of fields. More the fields , more the getter setters leading to frustration by verbosity * **/ }
Sample Java code using new records public record Customer(String FirstName, String LastName, String Addr1, String Addr2, String City ) {}

So if you have are working on a project that uses Java 14 or higher & your java class seems to have a lot of getter / setters, it is time for you to Java records. Here are some resources if you want to check out java records in detail

  • Java records overview by Oracle .
  • Most viewed/liked Youtube video on Java Records
  • Official specs
  • Java Refactoring

    Clicky