DevilKing's blog

冷灯看剑,剑上几分功名?炉香无需计苍生,纵一穿烟逝,万丈云埋,孤阳还照古陵

0%

Null Elegantly In Java Optional

原文链接

Optional is primarily intended for use as a method return type where there is a clear need to represent “no result,” and where using null is likely to cause errors. A variable whose type is Optional should never itself be null. It should always point to an Optional instance.

多尝试利用流式方式,而非简单的判断

1
2
3
Reservation reservation = reservationService.findById("notExistingId");
Optional<Reservation> optReservation = Optional.ofNullable(reservation);
List<ReservationDetail> reservatonDetails = optServation.map(Reservation::getDetails).orElse(Collections.emptyList())

a code without null check validation

To do a null check validation we won’t use if (objects == null) here, instead we use isPresent, ifPresent, orElse, orElseGet and orElseThrow.

I think Optional class is good when used inside a service, and returns at getter of the class attribute, But I don’t think it’ll be good when passes over parameter because it gives more ambiguity and it ignores the meaning of the parameter itself which is made to be filled.

可以尝试做一个optionalService?来处理需要判断null的情况,返回各种object或者什么