preface

Recently, I searched online and found that many people have mixed opinions about Lombok, which aroused my interest. Lombok is also widely used in our project, and I have been confused by their different opinions for a few days. Today, BASED on my actual project experience, I would like to share with you my personal suggestions.

A casual search turned up these articles:

These people suggested lombok as a magic tool that could greatly improve coding efficiency and make code more elegant.

While searching, some articles are not recommended:

These people feel that it has a few holes, easy to put a hidden danger to the project, who should we listen to?

Why is Lombok recommended?

1. The traditional javabean

Before Lombok, we used to define Javabeans like this:

public class User {

    private Long id;
    private String name;
    private Integer age;
    private String address;

    public User(a) {}public User(Long id, String name, Integer age, String address) {
        this.id = id;
        this.name = name;
        this.age = age;
        this.address = address;
    }

    public Long getId(a) {
        return id;
    }

    public String getName(a) {
        return name;
    }

    public Integer getAge(a) {
        return age;
    }

    public String getAddress(a) {
        return address;
    }


    public void setId(Long id) {
        this.id = id;
    }

    public void setName(String name) {
        this.name = name;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null|| getClass() ! = o.getClass())return false;
        User user = (User) o;
        return Objects.equals(id, user.id) &&
                Objects.equals(name, user.name) &&
                Objects.equals(age, user.age) &&
                Objects.equals(address, user.address);
    }

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

    @Override
    public String toString(a) {
        return "User{" +
                "id=" + id +
                ", name='" + name + '\' ' +
                ", age=" + age +
                ", address='" + address + '\' ' +
                '} '; }}Copy the code

The User class contains member variables, getter/setter methods, constructors, equals, and hashCode methods.

At first glance, there’s a lot of code. Also, if the code in the User class is changed, for example, the age field is changed to a string type, or the name of the name field is changed, do you need to synchronize the related member variables, getters/setters, constructors, equals, hashCode, all of them?

Maybe some friends will say: the current idea is very smart, you can fix the modification at one time.

Yeah, but there’s a more elegant way to do it.

2. The use of lombok

The first step is to introduce the JAR package

  <dependency>
      <groupId>org.projectlombok</groupId>
      <artifactId>lombok</artifactId>
      <version>1.184.</version>
      <scope>provided</scope>
  </dependency>
Copy the code

Step 2: Install the plug-in in IDEA

Note: If you do not follow the plugin idea, it will not compile and uselombokAnnotated code.

Third, use Lombok annotations in your code

The User class code above could look like this:

@ToString
@EqualsAndHashCode
@NoArgsConstructor
@AllArgsConstructor
@Getter
@Setter
public class User {

    private Long id;
    private String name;
    private Integer age;
    private String address;
}
Copy the code

So good, the code can be optimized to be so simple. The body of the User class only defines the member variables, leaving all the other methods to the annotations.

What if you change a member variable name or type?

@ToString
@EqualsAndHashCode
@NoArgsConstructor
@AllArgsConstructor
@Getter
@Setter
public class User {

    private Long id;
    private String userName;
    private String age;
    private String address;
}
Copy the code

You can just focus on changing the member variables, and you don’t have to worry about anything else. It’s so cool.

Even more exciting, it can be further optimized:

@NoArgsConstructor
@AllArgsConstructor
@Data
public class User {

    private Long id;
    private String userName;
    private String age;
    private String address;
}
Copy the code

@data is equivalent to the set of @getter, @setter, @toString, @equalSandhashCode, and @requiredargsConstructor.

Lombok notes are as follows:

Photo credit: Little Wolf

The biggest benefit of Using Lombok is that it’s a lot less code, a lot more efficient, and the code looks more elegant, which is a real gem.

How Lombok works

Java program parsing is divided into runtime parsing and compile-time parsing.

Typically, we get classes, methods, annotations, and member variables through reflection, which is runtime parsing. But this way is not efficient, in order to run the program can be resolved.

This is where compile-time parsing comes in handy.

Compile-time parsing is divided into Annotation Processing Tool and JSR 269 Pluggable Annotation Processing API.

The first type of processor, which was first introduced in JDK 1.5 along with annotations, is a command-line tool that provides build-time source-based reading of a program’s structure and the ability to influence the compilation process by running the Annotation processor to generate new intermediate files.

After JDK 1.8, however, the first processor was phased out in favor of the second processor. Let’s take a look at its processing flow:

The underlying implementation of Lombok is as follows:

  1. Javac analyzes the source code to generate an abstract syntax tree (AST)
  2. A Lombok program that implements the “JSR 269 API” is invoked during compilation
  3. Lombok then processes the AST obtained in the first step, finds the syntax tree (AST) corresponding to the class of the @data annotation, and modifies the AST to add the corresponding tree nodes defined by getter and setter methods
  4. Javac generates bytecode files using a modified abstract syntax tree (AST), which adds new nodes (code blocks) to the class

Why not recommend Lombok?

Even though Lombok is a gem, many people don’t recommend using it. Why?

1. Force teammates to install the IDEA plug-in

This is really gross, because writing code using Lombok annotations requires everyone involved in the development to install the Lombok plug-in for IDEA or the code will compile badly.

2. Code readability deteriorates

With Lombok annotations, you don’t actually see the resulting code, you see it as it was before it was modified. If you want to see a reference to a getter or setter method, it’s very difficult.

3. Upgrading JDK affects functions

When someone upgraded the JDK from Java 8 to Java 11, I found Lombok didn’t work properly.

4. There are some pits

  1. When using @data, @equalSandHashCode (callSuper=false) is used by default, and the generated equals() method only compares the attributes of the subclass, regardless of whether the attributes are inherited from the parent class.

  2. Use @Builder with @allargsconstructor, otherwise an error may be reported.

5. It is not easy to debug

Most of us like to debug to locate problems, but lombok generated code is not easy to debug.

6. Strong dependence on upstream and downstream systems

If the Fegin Client provided in the upstream system uses Lombok, then the downstream system must also use Lombok, otherwise an error will be reported, creating a strong dependency between the upstream and downstream systems.

How do we choose?

Lombok has pros and cons. How do we choose?

Personal advice to make the most reasonable choice according to the actual situation of the project.

  1. If you are working on a new project and the upstream and downstream systems are new, lombok is recommended as it can significantly improve development efficiency.
  2. If you are working on an old project and have not used Lombok before, it is recommended that you do not use lombok in the future because of the high cost of code changes. If you have used Lombok in the past, it is recommended that you use lombok in the future because of the high cost of code modification.
  3. In fact, as long as the introduction of JAR package may have: mandatory teammates install IDEA plug-in, upgrade JDK impact on the function, some pits and upstream and downstream systems are strongly dependent on these problems, as long as the development of good specifications, summed up the use of experience these problems.
  4. I don’t think lombok is a big problem because it’s used on Javabeans, and the logic of that class is relatively simple. A lot of code can be read at a glance, and you can guess 7 or 8 out of 10 without debugging.

One last word (attention, don’t fuck me for nothing)

If this article is of any help or inspiration to you, please scan the QR code and pay attention to it. Your support is the biggest motivation for me to keep writing.

Ask for a key three even: like, forward, look.