ChrisEades
ChrisEades

Reputation: 83

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.

Is there a better way to check getShopModel().getType() in such a way that I only need to call getShopModel() once?

Upvotes: 2

Views: 811

Answers (1)

Eran
Eran

Reputation: 22020

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'.

Upvotes: 5

Related Questions