简体   繁体   中英

How can i put a null check in a parameter of a method?

like

x = setDetailsFromSegment(getDetails.getProductList().getProductDetails().get(0).getItinerary().getOriginDestinationList(),
                          getDetailsResponse.getProductDetailsList().getProductDetails().get(0).getFareList());

Here setDetailsFromSegment() is my method and I want to check whether the parameters are null or not before invoking the method using java 8.

You should avoid the necessarity of null-checks if possible.

If you can change getOriginDestinationList() and getFareList() you should make them return Collections.emptyList() . If you are not returning lists, you might consider to use an java.util.Optional . But be careful where to use and Optional and where not. See for example Should Java 8 getters return optional type?

If you cannot change the return value of the methods, you have to execute the checks before you are calling the methods. Objects.requireNotNull() could be helpful here.

Beside this your code has a problem because of excessive method chaining. You might need to check the return values for every method. And it is hard to read. And I would not use "x" as a variable name ;-).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM