mercredi 5 juillet 2017

Is this correct usage of builder pattern in dtos?

Assume i have PostDTO that has this fields:

private Long id;
private ShortInfoUserDTO author;
private CategoryDTO category;

And i have CategoryDTO inside of it that also has Builder, and it has fields:

private Long id;
private String name;

And ShortInfoUserDTO has some fields (doesn't matter what fields, but it also has Builder)

And My builder pattern looks like this ( both CategoryDTO and

public static Builder builder() {
    return new PostDTO.Builder();
}
public static class Builder {
    PostDTO instance = new PostDTO();        

    public Builder id(Long id) {
        instance.id = id;
        return this;
    }

    public Builder author(User user) {
        ShortInfoUserDTO author = ShortInfoUserDTO.builder()
                                                  .id(user.getId())
                                            .username(user.getUsername())
                                            .build();
        instance.author = author;
        return this;
    }



    public Builder category(Category category) {
          CategoryDTO categoryDto = CategoryDTO
                                      .builder()
                                      .id(category.getId())
                                      .name(category.getName())
                                      .build();           

          instance.category = categoryDto;            
          return this;
    }

    public PostDTO build() {
        return instance;
    }
}

Is generally the idea of building author() and category() this way good? like is this proper architecture? One of the reason im asking is because i'm kinda worried about nullpointerexceptions

Aucun commentaire:

Enregistrer un commentaire