Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
366 views
in Technique[技术] by (71.8m points)

Lombok getter/setter vs Java 14 record

I love project Lombok but in 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 better to rely on the feature of Lombok or should we start using the record functionality:

Is 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 the both approach?

question from:https://stackoverflow.com/questions/61306802/lombok-getter-setter-vs-java-14-record

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...