Consider the following model:
class Student {
private int id;
private Boolean isPresent = Boolean.False;
}
Now if I build a student object using Builder pattern, while not setting the value for isPresent is 'null' and not 'false' as we have initialized.
Student model = Student.builder().id(10).build();
// model.isPresent is set as null instead of false
I want to know for this particular use case is there any way to set isPresent to false i.e initialize a Boolean variable when user does not sets the value in Builder pattern? Please note I am unable to use boolean instead of 'Boolean' or set value of isPresent in builder.
Edit: I am using Lombok to implement builder pattern. I am using All args constructor and no args constructor and getter, setter methods.
CodePudding user response:
I'm a bit confused about which of the two approaches you are using, so I am providing answer for both the below cases:
- Are you implementing the Builder Pattern?
- Are you using any framework which provides the builder pattern for you?
- If you are implementing the builder pattern you can initialize inside the
StudentBuilder
class this way:
class Student {
private final int id;
private Boolean isPresent = Boolean.FALSE;
Student(int id, Boolean isPresent) {
this.id = id;
this.isPresent = isPresent;
}
public static StudentBuilder builder() {
return new StudentBuilder();
}
public static class StudentBuilder {
private int id;
private Boolean isPresent = Boolean.FALSE;
StudentBuilder() {
}
public StudentBuilder id(int id) {
this.id = id;
return this;
}
public StudentBuilder isPresent(Boolean isPresent) {
this.isPresent = isPresent;
return this;
}
public Student build() {
return new Student(id, isPresent);
}
public String toString() {
return "Student.StudentBuilder(id=" this.id ", isPresent=" this.isPresent ")";
}
}
if you are using any framework like Lombok for the builder pattern,
You can replace the Boxed data type with primitive data types:
class Student { private int id; private boolean isPresent; //default is false. }
That will also result in the
false
Edit: Alternatively you can check for Null in the constructor and implement the logic by yourself.
Like:
@Getter
@Builder
class Student {
private int id;
private Boolean isPresent;
private Student(int id, Boolean isPresent) {
this.id = id;
this.isPresent = isPresent;
if (this.isPresent == null) {
this.isPresent = false;
}
}
Note: When using the builder
pattern you want to make the object as immutable after the build
. So don't make the setter
explicitly available, furthermore don't even allow the instantiation (make the constructor private).