Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 757
namalfernandolk Avatar asked May 29 '17 13:05

namalfernandolk


2 Answers

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);
}
like image 169
Sergey Kalinichenko Avatar answered Nov 09 '22 12:11

Sergey Kalinichenko


Option 3:

Optional.ofNullable(animalData)
    .map(animalData -> animalData.getBreedData())
    .ifPresent(breedData -> {
        Optional.ofNullable(dogx.getBreed())
            .map(breed -> breed.getBreedCode())
            .ifPresent(breedCode -> {
                thisBreedData = breedData.get(breedCode); // here we could use a third Optional call…
                if (thisBreedData != null) {
                    dogx.getBreed().setBreedId(thisBreedData));
                }
            }) 
    });
}
like image 43
glglgl Avatar answered Nov 09 '22 13:11

glglgl