I am here to ask quick question about builder and optionals. I have this simple example here:
public class User { private final String name; private final String lastname; private final String phone; private User(Builder builder) { this.name = builder.name; this.lastname = builder.lastname; this.phone = builder.phone; } public String getName() { return name; } public String getLastname() { return lastname; } public String getPhone() { return phone; } @Override public String toString() { return "User{" + "name='" + name + '\'' + ", lastname='" + lastname + '\'' + ", phone='" + phone + '\'' + '}'; } public static class Builder { private String name; private String lastname; private String phone = ""; public Builder(String name, String lastname) { name(name); lastname(lastname); } private Builder name(String name) { this.name = Optional.ofNullable(name).orElseThrow(() -> new IllegalArgumentException("Name must not be null")); return this; } private Builder lastname(String lastname) { this.lastname = Optional.ofNullable(lastname).orElseThrow(() -> new IllegalArgumentException("Last name must not be null")); return this; } public Builder phone(String phone) { this.phone = Optional.ofNullable(phone).orElse(""); return this; } public User build() { return new User(this); } }
}
So.. this code work as expected but I have some doubts. My question is about private methods in builder(name and lastname). Is it allowed in a world of a clean code? And also about this Optionals, are they well written? I just start using this functionality so I don’t know for sure if I am right here.