I am constructing a car class that has an engine, gearbox, clutch etc. I don't want a bloated constructor that takes 7 parameters, so I decided to use the builder pattern. All the parts are required. However, how do I make the user of the Car class use all the parts' setters, as they are all mandatory? Throw exceptions?
public class Car {
private Engine engine;
private Chassis chassis;
private GearBox gearBox;
private Coupe coupe;
private Exterior exterior;
private Interior interior;
private Clutch clutch;
public Car(Builder builder) {
engine = builder.engine;
chassis = builder.chassis;
gearBox = builder.gearBox;
coupe = builder.coupe;
exterior = builder.exterior;
interior = builder.interior;
clutch = builder.clutch;
}
public static class Builder {
private Engine engine;
private Chassis chassis;
private GearBox gearBox;
private Coupe coupe;
private Exterior exterior;
private Interior interior;
private Clutch clutch;
private Car build() {
return new Car(this);
}
public Builder setEngine(@NonNull Engine engine) {
this.engine = engine;
return this;
}
public Builder setChassis(@NonNull Chassis chassis) {
this.chassis = chassis;
return this;
}
public Builder setGearBox(@NonNull GearBox gearBox) {
this.gearBox = gearBox;
return this;
}
public Builder setCoupe(@NonNull Coupe coupe) {
this.coupe = coupe;
return this;
}
public Builder setExterior(@NonNull Exterior exterior) {
this.exterior = exterior;
return this;
}
public Builder setInterior(@NonNull Interior interior) {
this.interior = interior;
return this;
}
public Builder setClutch(@NonNull Clutch clutchs) {
this.clutch = clutchs;
return this;
}
}
}
I want the user so call ALL of the builder setters, not an optional subset of them. How do I do that?
Is there another way to construct a car without having a huge constructor that takes so many parameters?
EDIT: I looked at The builder pattern and a large number of mandatory parameters but there is no solution there that prevents huge constructors.