I have the following DTO:
@Data
public class MenuItemDTO {
private UUID siteUuid;
private UUID productUuid;
private boolean outOfStock;
public MenuItemDTO(MenuItem menuItem, boolean outOfStock) {
this.siteUuid = menuItem.getSiteUuid();
this.productUuid = menuItem.getProductUuid();
this.outOfStock = outOfStock;
}
}
I have not outOfStock
field in MenuItem
entity and I want to fill outOfStock
field if the record is not empty (I just keep the out of stocked products). But I am not sure if there is a proper way using stream:
public List<MenuItemDTO> findAllBySiteBrandUuid(UUID siteUuid) {
return menuItemRepository.findAllBySiteUuid(siteUuid)
.stream()
.map(m -> new MenuItemDTO(m, m.getUuid() != null))
.collect(Collectors.toList());
}
1. As I do not keep outOfStock
field in MenuItem
entity, is my approach in MenuItemDTO
a proper way?
2. I am wondering if there is a more elegant way by using stream properly for .map(m -> new MenuItemDTO(m, m.getUuid() != null))
part.
CodePudding user response:
There's quite some duplication. You're passing an object and a field of an object to the constructor. Maybe the more elegant way would be to avoid passing the information twice by moving the logic to the constructor:
public MenuItemDTO(MenuItem menuItem) {
this.siteUuid = menuItem.getSiteUuid();
this.productUuid = menuItem.getProductUuid();
this.outOfStock = menuItem.getUuid() != null;
}
And then the stream mapping reduces to:
public List<MenuItemDTO> findAllBySiteBrandUuid(UUID siteUuid) {
return menuItemRepository.findAllBySiteUuid(siteUuid)
.stream()
.map(MenuItemDTO::new)
.collect(Collectors.toList());
}
The information in the DTO is whatever client needs, so it's not up to us to decide if putting boolean there is the right way. I'd say it's good if that's what will be used on the client side.