Java Records: Why They're More Than Just DTOs
One of the magic features of Java 16 is Java Records, which was previewed in Java 14. It was designed specifically for carrying data like a class but without boilerplate code and not permitting modification by providing the immutability concept implementation.
One of its major benefits is:
Eliminating boilerplate code:
Automation of the generation of constructors and getters, and other functions like hashcode(), toString(), and equals().
Immutability by default:
All fields are implicitly final.
Clarity:
Readable and signals that the class is a data container.
Comparison between old and new approach:
NEW:
public record Car(String name, String color, String number){}
OLD:
public class Car{
private final String name;
private final String color;
private final String number;
public Car(String name, String color, String number) {
this.name = name;
this.color= color;
this.number= number;
}
public String getName() {
return name;
}
public String getColor() {
return color;
}
public String getNumber() {
return number;
}
@Override public boolean equals(Object o) { /* ... implementation ... */ }
@Override public int hashCode() { /* ... implementation ... */ }
@Override public String toString() { /* ... implementation ... */ }
}

Comments
Post a Comment