SO, I have class that uses @Builder lombok annotation. This is how it looks and how I use it:
import lombok.Builder; import lombok.Data; import com.fasterxml.jackson.annotation.JsonProperty; @Data @Builder public class MyModel { @JsonProperty(value = "myField1") private String myField1; @JsonProperty(value = "myField2") private String myField2; @JsonProperty(value = "myField3") private String myField3; } //This is how I use it: MyModel model = MyModel.builder() .myField1("value for field 1") .myField2("value for field 2") .build();
My question is if it is a good practice or not to add some additional method to this class? Or I should leave it as it is and do any business logic outside??
Basically, lets say, I need a helper method to set myField3 property, because I CANNOT just to do:
.myField3("value for field 3") .build()
I need to perform some actions on value for field3 and after that set it to MyModel.
So can I put this helper method to this class?
According to Lombok's Builder documentation ,
Each listed generated element will be silently skipped if that element already exists (disregarding parameter counts and looking only at names). This includes the builder itself: If that class already exists, lombok will simply start injecting fields and methods inside this already existing class, unless of course the fields / methods to be injected already exist. You may not put any other method (or constructor) generating lombok annotation on a builder class though; for example, you can not put @EqualsAndHashCode on the builder class.
So can I put this helper method to this class?
Yes, you can by having a minimal builder which provides a method with the same name as the field, ie, myField3
. The business logic can be added to this method. Here is a simple example where "Hello" is prepended to the value provided by the setter,
@Data
@Builder
public class MyModel {
private String myField1;
private String myField2;
private String myField3;
public static class MyModelBuilder {
public MyModelBuilder myField3(String myField3) {
this.myField3 = "Hello " + myField3;
return this;
}
}
}
Here is an example of using your class,
MyModel model = MyModel.builder()
.myField1("value for field 1")
.myField2("value for field 2")
.myField3("value for field 3")
.build();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.