Using try-catch over if conditions to safely set values with minimum performance impact in java

namalfernandolk :

Here, my main goal is setting the value safely, without having a performance (speed, memory, cpu etc) impact.

I have a silly option (in a bad style) also mentioned below. So, what is the best way to do this? option 1? option 2? or another one?

Option 1 :

if(
    animalData!=null && 
    animalData.getBreedData()!=null && 
    dogx.getBreed() != null && dogx.getBreed().getBreedCode() != null && 
    animalData.getBreedData().get(dogx.getBreed().getBreedCode()) != null
){
    dogx.getBreed().setBreedId(animalData.getBreedData().get(dogx.getBreed().getBreedCode()));
}

Option 2 :

try{dogx.getBreed().setBreedId(animalData.getBreedData().get(dogx.getBreed().getBreedCode()));}catch(Exception e){}

Note : this piece of code is in a loop having many thousands of iterarations.

dasblinkenlight :

Checking for nulls is the only option that is consistent with Java exception philosophy.

NullPointerException is a RuntimeException, which means that it is designed for reporting programming errors. This makes it an extremely bad practice to use it for anything other than terminating your program.

You can optimize your code by storing references to objects for null-checking, so that you can reuse them later:

BreedData breedData;
DogBreed dogBreed;
String breedCode;
String breedId;
if( animalData != null
&&  (breedData = animalData.getBreedData())!=null
&&  (dogBreed = dogx.getBreed()) != null
&&  (breedCode = dogx.getBreed().getBreedCode()) != null
&&  (breedId = breedData.get(breedCode)) != null
) {
    dogBreed.setBreedId(breedId);
}

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=467655&siteId=1