Optionalis primarily intended for use as a method return type where there is a clear need to represent “no result,” and where usingnullis likely to cause errors. A variable whose type isOptionalshould never itself benull. It should always point to anOptionalinstance.
多尝试利用流式方式,而非简单的判断
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或者什么