mardi 6 décembre 2016

try..catch VS long if()

I have a complex model structure in my project.
Sometimes I have to get a deep placed value from it. It looks like following:

something.getSomethongElse().getSecondSomething().getThirdSomething().getFourthSomething();

The problem is that each of those methods could return null, and I will get NullPointerException in case if it does.

What I want to know is should I write long if like

if(something != null && something.getSomethongElse() != null && something..getSomethongElse().getSecondSomething() != null && something.getSomethongElse().getSecondSomething().getThirdSomething() != null && omething.getSomethongElse().getSecondSomething().getThirdSomething().getFourthSomething() != null) {
    //process getFourthSomething result.
}

Or it is OK just to use try..catch like following:

SomethingFourth fourth = null;

try {
    fourth = something.getSomethongElse().getSecondSomething().getThirdSomething().getFourthSomething();
} catch (NullPointerException e) { }

if(fourth != null) {
    ///work with fourth
}

I know that NPE is a thing to be avoided, but isn't it overhead to avoid it in my case?

Aucun commentaire:

Enregistrer un commentaire