Imagine I have a class that encapsulates another class:
@Builder
public class Dragon {
private Dimensions dimensions;
private String name;
public static class ParentBuilder {
DimensionsBuilder innerBuilder = Dimensions.builder();
public DragonBuilder height(double height) {
this.innerBuilder.height(height);
return this;
}
public DragonBuilder length(double length) {
this.innerBuilder.length(length);
return this;
}
public Dragon build() {
return Dragon.builder()
.dimensions(this.innerBuilder.build())
.name(this.name)
.build();
}
}
}
@Builder
public class Dimensions {
private double height;
private double length;
}
Keep in mind that this is a very simplified example, the real code (which is, unfortunately, not about dragons) delegates a lot of properties to the innerBuilder
.
This way, I can instantiate the class like this:
Dragon dragon = Dragon.builder()
.height(12.0)
.length(25.0)
.name("Smaug")
.build();
Instead of like this:
Dragon dragon = Dragon.builder()
.dimensions(Dimensions.builder()
.height(12.0)
.length(25.0)
.build())
.name("Smaug")
.build;
Is it good coding practice to add builder methods to directly build the inner class too? Or does it offend some design principle, because maybe it's too tightly coupled?
One issue I already encountered was when doing a refactor of the inner class, I also had to apply mostly the same refactorings to the parent class.
Aucun commentaire:
Enregistrer un commentaire