简体   繁体   English

空检查Java中的嵌套方法调用

[英]Null Checking Nested Method Calls in Java

I need to null check nested method calls like so: 我需要对嵌套方法调用进行空检查,如下所示:

if (getShopModel() != null && getShopModel().getType() != null)

I don't think this is the best way to do it though as I am calling getShopModel twice which could be quite expensive. 我不认为这是最好的方法,尽管我两次调用getShopModel可能会非常昂贵。

Is there a better way to check getShopModel().getType() in such a way that I only need to call getShopModel() once? 有没有更好的方法来检查getShopModel()。getType(),而我只需要调用一次getShopModel()?

Use a variable... 使用变量...

Model model = getShopModel();
if (model != null && model.getType() != null)

This costs you nothing, saves an extra call, and might even make it easier to debug should you be interested of the value returned by 'getShopModel'. 如果您对'getShopModel'返回的值感兴趣,这将使您不花任何钱,节省一个额外的调用,甚至可能使调试变得更容易。

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

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