Optional
is primarily intended for use as a method return type where there is a clear need to represent “no result,” and where usingnull
is likely to cause errors. A variable whose type isOptional
should never itself benull
. It should always point to anOptional
instance.
多尝试利用流式方式,而非简单的判断
1 | Reservation reservation = reservationService.findById("notExistingId"); |
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或者什么