I am in the process of using Java Builder design pattern to write a connector class that has optional member variables and need some suggestions. My question from here Standard practices for employing Java Builder design pattern has been updated and the code now presented is not psuedocode but is specific.
public class Connector {
// Instance variables
String appUrl = null;
String oneTimePwd = null;
String accessKey = null;
// Private constructor
private Connector(Builder builder) {
this.appUrl = builder.appUrl;
this.accessKey = builder.accessKey;
this.oneTimePwd = builder.oneTimePwd;
}
public static class Builder {
// Instance variables
String appUrl = null;
String accessKey = null;
String oneTimePwd = null;
public Builder() {
// Empty constructor that accepts no arguments.
}
// Setter method for mandatory field/s
public Builder setMandatoryParameters(String appUrl) {
this.appUrl = appUrl;
return this;
}
// Setter method1 for optional field/s
public Builder setAccessKey(String accessKey) {
this.accessKey = accessKey;
return this;
}
// Setter method2 for optional field/s
public Builder setOneTimePwd(String oneTimePwd) {
this.oneTimePwd = oneTimePwd;
return this;
}
public Connector Build() {
if (accessKey != null) {
return new Connector(this);
} else if (oneTimePwd != null) {
return new Connector(this);
} else {
// log.error("Either Access key or One time password must be specified.")
}
return null;
}
}
// Other methods of the Connector class
// ...
}
Question 1: Is it sensible to make use of a method "setMandatoryParameters()" to obtain values for mandatory parameters? This will allow creation of an instance of the Builder without supplying the mandatory parameters which can be a drawback. Is it much better to ask the user to supply the values for mandatory parameters with Builder's constructor?
Question 2: Either access key or one time password is needed to establish a successful connection. Thus, field validations such as null checks have been employed in the "Build()" method. Should such validations be performed in the Connector class's constructor instead?