为什么要请谨慎使用 @Builder 注解

大多数同学使用 @Builder 无非就是为了链式编程,然而 @Builder 并不是链式编程的最佳实践,它会额外创建内部类,存在继承关系时还需要使用 @SuperBuilder 注解[2],设置默认值时也需要额外的 @Builder.Default 去设置默认值[3],无疑增加了很多不必要的复杂度。

有些同学可能说如果你把这些问题都了解就不会遇到这些坑,没必要“因噎废食”,可是这些问题已经让无数人一次次趟坑,说明它并不是最佳实践,如果有更简便办法可以实现链式编程,又何必徒增这么多复杂度呢?其实很多人选择使用 @Builder 实现链式编程,无非是它“更常见”和“最熟悉” !

二、为什么?

(1)@Builder 生成的构造器不是完美的,它不能区分哪些参数是必须的,哪些是可选的。如果没有提供必须的参数,构造器可能会创建出不完整或者不合法的对象。

可以看第三部分的例子, @Builder 注解产生的 Builder 类的构造方法默认并不能限定必传参数。

(2)很多人 喜欢 @Builder 和 @Data 搭配使用,导致生成的构造器是可变的,它允许使用 setter 方法修改构造器的状态。这违反了构造器模式的原则,构造器应该是不可变的,一旦创建就不能被修改。

如果非要使用 @Builder ,那么不要用 @Data ,要用 @Getter。相对来说,反而 @Accessors 的行为更符合这个要求。

(3)@Builder 生成的构造器不适合用于短暂的对象,它会增加代码的复杂度和冗余。构造器模式更适合用于生命周期较长、有多种变体的对象。

实际使用中经常发现 @Builder 滥用的情况,有些仅仅一两个属性的类也都要用 @Builder,真的没必要用,直接用全参的构造方法都比这更简洁。

(4)@Builder 生成的构造器不能处理抽象类型的参数,它只能接受具体类型的对象。这限制了构造器的灵活性和扩展性,不能根据不同的需求创建不同风格的对象。(5)继承关系时,子类需要使用 @SuperBuilder。对象继承后,子类的 Builder 因为构造函数的问题,使用不当大概率会报错,并且无法设置父类的属性,还需要使用 @SuperBuilder 来解决问题。(6)设置默认值需要使用 @Builder.Default。很容易因为对此不了解,导致默认值不符合预期导致出现 BUG。

三、怎么做?

正如 《Oh !! Stop using @Builder》 所推荐的一样,建议使用 @Accessors(chain = true) 来代替。

3.1 不使用 @Builder

package io.gitrebase.demo;

import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@NoArgsConstructor
@AllArgsConstructor
public class APIResponse<T> {

    private T payload;

    private Status status;

}

使用示例:

package io.gitrebase.demo;

import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@Slf4j
@RestControllerAdvice(assignableTypes = io.gitrebase.demo.RestApplication.class)
public class ApplicationExceptionHandler {

    @ResponseStatus(code = HttpStatus.INTERNAL_SERVER_ERROR)
    public APIResponse handleException(Exception exception) {
        log.error("Unhandled Exception", exception);
        Status status = new Status();
        status.setResponseCode("RESPONSE_CODE_IDENTIFIER");
        status.setDescription("Bla Bla Bla");
        APIResponse response = new APIResponse();
        response.setStatus(status);
        return response;
    }

}

3.2 使用 @Builder

package io.gitrebase.demo;

import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;

@Builder
@Data
@NoArgsConstructor
@AllArgsConstructor
public class APIResponse<T> {

    private T payload;

    private Status status;

}

等价代码:

package io.gitrebase.demo;

import lombok.AccessLevel;
import lombok.AllArgsConstructor;
import lombok.Getter;

@Getter
// Make constructor private so object cannot be created outside the class
// Allowing only PersonBuilder.build to create an instance of the class
@AllArgsConstructor(access = AccessLevel.PRIVATE)
public class Person {

    private String firstName;
    private String lastName;
    private String email;
    private String mobile;

    // PersonBuilder can only be created with  firstName, lastName
    // which implies that Person object ll always be instantiated with firstName & lastName
    public static PersonBuilder builder(String firstName, String lastName) {
        return new PersonBuilder(firstName, lastName);
    }

    public static class PersonBuilder {

        private final String firstName;
        private final String lastName;
        private String email;
        private String mobile;

        // Make constructor private so object cannot be created outside the class
        // Allowing only Person.builder to create an instance of  PersonBuilder
        private PersonBuilder(String firstName, String lastName) {
            this.firstName = firstName;
            this.lastName = lastName;
        }

        public PersonBuilder email(String email) {
            this.email = email;
            return this;
        }

        public PersonBuilder mobile(String mobile) {
            this.mobile = mobile;
            return this;
        }

        public Person build() {
            return new Person(firstName, lastName, email, mobile);
        }

    }

}

使用示例:

package io.gitrebase.demo;

import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@Slf4j
@RestControllerAdvice(basePackageClasses = io.gitrebase.demo.RestApplication.class)
public class ApplicationExceptionHandler {

    @ResponseStatus(code = HttpStatus.INTERNAL_SERVER_ERROR)
    public APIResponse handleException(Exception exception) {
        log.error("Unhandled Exception", exception);
        return APIResponse.builder().status(Status.builder()
                .responseCode("RESPONSE_CODE_IDENTIFIER")
                .description("Bla Bla Bla")
                .build())
                .build();
    }

}

3.3 使用 @Accessors 注解

package io.gitrebase.demo;

import lombok.Data;
import lombok.experimental.Accessors;


@Data
@Accessors(chain = true)
public class APIResponse<T> {

    private T payload;

    private Status status;

}

等价代码:

package io.gitrebase.demo;

import lombok.experimental.Accessors;

@Accessors(chain = true)
public class APIResponse<T> {

    private T payload;

    private Status status;

    public T getPayload() {
        return this.payload;
    }

    public APIResponse<T> setPayload(T payload) {
        this.payload = payload;
        return this;
    }

    public Status getStatus() {
        return this.status;
    }

    public APIResponse<T> setStatus(Status status) {
        this.status = status;
        return this;
    }
}

使用示例:

package io.gitrebase.demo;

import lombok.extern.slf4j.Slf4j;
import lombok.var;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@Slf4j
@RestControllerAdvice(basePackageClasses = io.gitrebase.demo.RestApplication.class)
public class ApplicationExceptionHandler {

    @ResponseStatus(code = HttpStatus.INTERNAL_SERVER_ERROR)
    public APIResponse handleException(Exception exception) {
        log.error("Unhandled Exception", exception);
        var status = new Status().setResponseCode("RESPONSE_CODE_IDENTIFIER").setDescription("Bla Bla Bla");
        return new APIResponse().setStatus(status);
    }

}

原文中给的示例相对简单,实际运用时,如果属性较多,且分为必传属性和选填属性时,可以将必传参数定义在构造方法中,加上 @Accessors 注解,这样就可以实现必传参数的传入,又可以实现选填参数的链式调用。

假设 Student 类,它的 学生ID和年级和班级是必填的,姓名、性别、住址是选填的,那么示例代码如下:

import lombok.Accessors;

// 使用 @Accessors 注解,设置 chain = true,生成返回 this 的 setter 方法
@Accessors(chain = true)
public class Student {
    // 定义必传属性,使用 final 修饰,不提供 setter 方法
    private final int studentId; // 学生ID
    private final int grade; // 年级
    private final int classNum; // 班级

    // 定义选填属性,提供 setter 方法
    private String name; // 姓名
    private String gender; // 性别
    private String address; // 住址

    // 定义构造方法,接收必传参数
    public Student(int studentId, int grade, int classNum) {
        this.studentId = studentId;
        this.grade = grade;
        this.classNum = classNum;
    }

    // 省略 getter 和 setter 方法
}

// 使用示例
Student student = new Student(1001, 3, 8) // 创建一个学生对象,传入必传参数
        .setName("张三") // 设置姓名
        .setGender("男") // 设置性别
        .setAddress("北京市朝阳区"); // 设置住址

另外该注解还有很多设置项,感兴趣可以进一步研究:

展开阅读全文

本文系作者在时代Java发表,未经许可,不得转载。

如有侵权,请联系nowjava@qq.com删除。

编辑于

关注时代Java

关注时代Java