Home > Back-end >  How to populate a list using the builder pattern in Java
How to populate a list using the builder pattern in Java

Time:08-12

I have this class which has a builder:

public class FieldValidationResponse {

  private Integer status;

  private String message;

  private List<FieldValidationError> errors;
  
}

I can build a FieldValidationResponse with an individual FieldValidationError like this:

private FieldValidationResponse fieldValidationResponse(String responseMessage, String message) {
    return FieldValidationResponse.builder()
        .message(responseMessage)
        .status(400)
        .error(
            FieldValidationError.builder()
                .message(message)
                .build()
        )
        .build();
}

Or I could build a FieldValidationResponse with multiple FieldValidationError like this:

private FieldValidationResponse fieldValidationResponse2(String responseMessage, List<String> messages) {
    List<FieldValidationError> fieldValidationErrors = new ArrayList<>();
    for (String message : messages) {
        fieldValidationErrors.add(
            FieldValidationError.builder()
                .message(message)
                .build()
        );
    }

    return FieldValidationResponse.builder()
        .message(responseMessage)
        .status(400)
        .errors(fieldValidationErrors)
        .build();
}

I feel that the way I am populating that list of FieldValidationError in the second method using the builder is not the "most elegant" way, I was wondering if I could improve that second method to populate a list?

CodePudding user response:

can be achieved using stream.

  private FieldValidationResponse fieldValidationResponse2(
      String responseMessage, List<String> messages) {

    return FieldValidationResponse.builder()
        .message(responseMessage)
        .status(400)
        .errors(messages.stream().map(this::buildError).collect(Collectors.toList()))
        .build();
  }

  private FieldValidationError buildError(String message) {
    return FieldValidationError.builder().message(message).build();
  }

CodePudding user response:

I would add a method to FieldValidationResponse's builder that can take a list of messages and adds a FieldValidationError to itself for each one. Something like this (untested pseudo-code):

public FieldValidationResponseBuilder withErrors(List<String> messages) {
    for (String message : messages) {
        this.withError(message);
    }

    return this;
}

public FieldValidationResponseBuilder withError(String message) {
    this.errors.add(
            FieldValidationError.builder()
                .message(message)
                .build());

    return this;
}

The you'd use it like this:

    return FieldValidationResponse.builder()
        .message(responseMessage)
        .status(400)
        .withErrors(messages)
        .build();

A side benefit is that this also simplifies your first method a little bit.

  • Related