I love project Lombok but these days I'm reading and trying some of the new features of Java 14.
Inside the new capability, there is the record keyword that allows creating a class with already built-in the following functionality: constructor, private final fields, accessors, equals/hashCode, getters, toString methods.
Now my question is: is it better to rely on the feature of Lombok or should we start using the record functionality:
Is it better to use this:
record Person (String name, String surname) {}
or that:
@AllArgsConstructor
@ToString
@EqualsAndHashCode
public class Person {
@Getter private int name;
@Getter private int surname;
}
What are the pros and cons of both approaches?
Lombok, and the record
feature of the Java language, are different tools for different things. There is some superficial overlap, but don't let that distract you.
Lombok is largely about syntactic convenience; it is a macro-processor pre-loaded with some known useful patterns of code. It doesn't confer any semantics; it just automates the patterns, according to some knobs you set in the code with annotations. Lombok is purely about the convenience of implementing data-carrying classes.
Records are a semantic feature; they are nominal tuples. By making a semantic declaration that Point
is a tuple of (int x, int y)
, the compiler can derive its representation, as well as construction, declaration, equality, hashing, and string representation protocols, from this state description. Because they carry semantics, readers and frameworks can also reason with higher confidence about the API of records. (This may also be syntactically convenient; if so, that's great.)