I have a list of product price objects, List<ProductPrice>
.
@Value
public class ProductPrice {
Long id;
LocalDate startDate;
LocalDate endDate;
BigDecimal value;
}
From the list I need to find prices that have a start date equal to or greater than a given start date AND an end date equal to or before the end date. I do that via:
List<ProductPrice> pricesInDateRange = productPrices.stream()
.filter(p -> p.getStartDate().equals(startDate) || p.getStartDate().isAfter(startDate))
.filter(p -> p.getEndDate().equals(endDate) || p.getEndDate().isBefore(endDate))
.collect(Collectors.toList());
I need to also make sure that one price has a start date equal to the given start date and same of end date.
Finally, I need to perform some calculations on the list of ProductPrice
objects using the value
field. For example,
pricesInDateRange
.stream()
.map(value -> value.add(BigDecimal.ONE))
.reduce(BigDecimal.ONE, BigDecimal::multiply);
Should I create a class to wrap List<ProductPrice>
for a given date range and encapsulate the calculations? For example,
@Data
public class ProductPrices {
private List<ProductPrice> productPrices;
public ProductPrices getPricesInDateRange(LocalDate startDate, LocalDate endDate) {
return new ProductPrices(productPrices.stream()
.filter(p -> p.getStartDate().equals(startDate) || p.getStartDate().isAfter(startDate))
.filter(p -> p.getEndDate().equals(endDate) || p.getEndDate().isBefore(endDate))
.collect(Collectors.toList()));
}
public BigDecimal calculation1() {
productPrices
.stream()
.map(value -> value.add(BigDecimal.ONE))
.reduce(BigDecimal.ONE, BigDecimal::multiply);
}
Or should I do these operations in the service layer instead of a domain object? In other words, don't encapsulate in a ProductPrices
class.