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.
Checking for null
s 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);
}
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));
}
})
});
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With