I'm reading XML into JAXB pojos and want to merge fields to my entity pojos. But I don't want to overwrite the existing values if the value from the XML is null (ie. the value did not exist in the XML). So now I have long sets of code like this:
if (addressDetails.getNAME1() != null) {
org.setName1(addressDetails.getNAME1());
}
if (addressDetails.getNAME2() != null) {
org.setName2(addressDetails.getNAME2());
}
if (addressDetails.getNAME3() != null) {
org.setName3(addressDetails.getNAME3());
}
This is ugly, noisy and Sonar screams about cyclomatic complexity. How would you go about doing this? Things that come to mind:
I'm aiming for something readable and without lots of extra code.
Take a look at Google's Guava code library. It has some utility methods for dealing with nulls.