9D3.RW-Separation Dto
OriginalPracticeManualLess than 1 minute
9D3.RW-Separation Dto
In Wings, to protect data and prevent method leak, the incoming Dto should be read-only.
Getter and Builder
@Getter @Builder
@ToString @EqualsAndHashCode
public class RwsDto {
private Long id;
private String name;
}
The simplest separation strategy, with lombok power, and very clean code.
RwsDto p = RwsDto.builder()
.id(1L)
.name("name")
.build();
Builder Plugin
@Getter
@ToString @EqualsAndHashCode
public final class RwsDto {
private final Long id;
private final String name;
// Alt + Insert > Builder
}
In IDEA use InnerBuilder, and check the following options,
- Generate builder methods for final fields
- Generate static newBuilder()method
- Rename newBuilder()to builder()
- Generate builder copy constructor
In comparison to lombok, you can add your own code in the generated builder method.
Manual Inheritance
Builder pattern, mainly final + same field assignment pattern, the following is the inheritance way.
@Getter
@ToString @EqualsAndHashCode
public class RwsDto {
protected Long id;
protected String name;
public static Builder builder() {return new Builder();}
public static class Builder extends RwsDto {
public Builder() {
// int the fixed values
}
public Builder id(Long id){
Objects.requireNonNull(id);
super.id = id;
return this;
}
public Builder name(String name){
super.name = name;
return this;
}
public RwsDto build(){
return this;
}
}
}