Search code examples
javalombokbuilder

Condition based builder in Java


I have a field that needs to be checked. If the field matches put it to builder if not, don't put it to builder.

@Data
@Builder
public class UserSchool {
    private final Long UserId;
    private final String school;
    private final Optional<String> lunch;

}

I need to check if user belongs to "high school", then add parameter lunch to builder. If user doesn't belong to "high school" don't add parameter to builder.

if(user.school.name().equals(School.high_school.name())){
            Deposit.builder()
                    .lunch(request.getLounchName());
        }

UserSchool userSchool = UserSchool.builder()
                .UserId(Long.valueOf(user.UserId.id))
                .school(request.getUserSchool())
                .build();

I have come up with this code above and lunch parameter is null although it should be there.

When I add it to builder without if statement like this:

UserSchool userSchool = UserSchool.builder()
                .UserId(Long.valueOf(user.UserId.id))
                .school(request.getUserSchool())
                .lunch(request.getLounchName())
                .build();

It works but I need to be able to check condition. What am I missing?


Solution

  • You shouldn't use an Optional type as a class field, generally only return types or wrappers to nullable return types.

    If I understand the question, though, you're looking for this

    UserSchool.Builder builder = UserSchool.builder()
                    .UserId(Long.valueOf(user.UserId.id))
                    .school(request.getUserSchool());
    if (condition) {
       builder.lunch(..);
    }
    UserSchool userSchool = builder.build();
    

    Or

    String lunch = condition ? "some value" : null;
    UserSchool.Builder builder = UserSchool.builder()
                    .UserId(Long.valueOf(user.UserId.id))
                    .lunch(lunch)
                    .school(request.getUserSchool())
                   .build();
    

    Or simply add a method to the class, not use a nullable field

    public Optional<String> getLunch() {
        return condition ? Optional.of("some value") : Optional.empty();
    } 
    

    The problem with the if statement before the builder is that you've used some other builder, but never captured its return value to use later on