Required arguments with a Lombok @Builder

前端 未结 9 2494
天涯浪人
天涯浪人 2020-12-12 15:17

If I add @Builder to a class. The builder method is created.

Person.builder().name(\"john\").surname(\"Smith\").build();

I have a requirem

9条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-12 15:55

    I would recommend against this approach, as you will struggle to apply it consistently on other objects. Instead, you can just mark fields with @lombok.NonNull annotation and Lombok will generate null checks for you in the constructor and setters, so that Builder.build() will fail, if those fields are not set.

    Using builder pattern allows you to have very clear identification of which fields you're setting to which values. This is already lost for name field in your example, and it will further be lost for all other required fields, if you're building an object with multiple required fields. Consider the following example, can you tell which field is which just by reading code?

    Person.builder("John", "Michael", 16, 1987) // which is name, which is surname? what is 16?
        .year(1982) // if this is year of birth, then what is 1987 above?
        .build()
    

提交回复
热议问题