如何避免获取可选参数的方法中的if语句

时间:2017-04-20 09:06:46

标签: java spring-data-jpa spring-restcontroller

当我们有带可选参数的服务方法时,如何避免if语句?以下是示例。此时只有3个参数是可选的,我必须有许多if语句。是否存在解决此问题的设计模式?

public List<Order> getForHotelOrders(Long hotelId, Optional<LocalDate> fromDate, Optional<LocalDate> toDate, Optional<List<String>> paymentTypes) {
    List<Order> orders;
    if (fromDate.isPresent() && toDate.isPresent()) {
        if (paymentTypes.isPresent()) {
            orders = orderRepository.getForHotel(hotelId, fromDate.get(), toDate.get(), paymentTypes.get());
        } else {
            orders = orderRepository.getForHotel(hotelId, fromDate.get(), toDate.get(), Arrays.asList("CASH", "CARD"));
        }
    } else {
        if (paymentTypes.isPresent()) {
            orders = orderRepository.getForHotel(hotelId, paymentTypes.get());
        } else {
            orders = orderRepository.getForHotel(hotelId, Arrays.asList("CASH", "CARD"));
        }

    }
    return orders;
}

2 个答案:

答案 0 :(得分:2)

我会使用orElse

static final List<String> CASH_CARD = Arrays.asList("CASH", "CARD");

public List<Order> getForHotelOrders(Long hotelId, 
                                     Optional<LocalDate> fromDate, 
                                     Optional<LocalDate> toDate, 
                                     Optional<List<String>> paymentTypes) {
    List<String> paymentTypes2 = paymentTypes.orElse(CASH_CARD);
    return fromDate.isPresent() && toDate.isPresent() 
       ? orderRepository.getForHotel(hotelId, fromDate.get(), toDate.get(), paymentTypes2)
       : orderRepository.getForHotel(hotelId, paymentTypes);
}

public List<Order> getForHotelOrders(long hotelId, 
                                     Optional<LocalDate> fromDate, 
                                     Optional<LocalDate> toDate, 
                                     Optional<List<String>> paymentTypes) {
    return orderRepository.getForHotel(hotelId, 
                                       fromDate.orElse(LocalDate.MIN),
                                       toDate.orElse(LocalDate.MAX),
                                       paymentTypes.orElse(CASH_CARD));
}

BTW:如果您要避免null值,我会hotelId longOptionalLong。可空的Long似乎不一致。

答案 1 :(得分:1)

可以使用orElse(默认),克服多个if else ...

public List<Order> getForHotelOrders(Long hotelId, Optional<LocalDate> fromDate, Optional<LocalDate> toDate, Optional<List<String>> paymentTypes) {
    List<Order> orders;
    LocalDate defaultDate = LocalDate.now();
    orders = orderRepository.getForHotel(hotelId, fromDate.orElse(defaultDate), toDate.orElse(defaultDate), paymentTypes.orElse(Arrays.asList("CASH", "CARD")));
    return orders;
}