简体   繁体   English

如何在方法的参数中放入空检查?

[英]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. 这里的setDetailsFromSegment()是我的方法,我想在使用Java 8调用该方法之前检查参数是否为null。

You should avoid the necessarity of null-checks if possible. 如果可能的话,您应该避免空检查的必要性。

If you can change getOriginDestinationList() and getFareList() you should make them return Collections.emptyList() . 如果可以更改getOriginDestinationList()getFareList() ,则应使它们返回Collections.emptyList() If you are not returning lists, you might consider to use an java.util.Optional . 如果不返回列表,则可以考虑使用java.util.Optional But be careful where to use and Optional and where not. 但要小心在何处使用和可选,在何处不使用。 See for example Should Java 8 getters return optional type? 例如参见Java 8 getters是否应返回可选类型?

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. Objects.requireNotNull()在这里可能会有所帮助。

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 ;-). 而且我不会将“ x”用作变量名;-)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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