I'm working on an Spring Integration application that transforms a XML (converted by Jaxb) into a custom Object by checking various information given in the XML.
The problem is that I can't trust the data that has been sent to me and I have to do null checks everywhere. Can't decide if storing the result of a null check is better or is there another solution?
Solution 1: Do the null checks everywhere, and when we call another method, do the same null checks when needed. Which I dislike very much.
public void mapSpecificField(XmlObject xmlObject) {
if (xmlObject != null) {
if (xmlObject.getName() != null) {
if (xmlObject.getName().equals("TYPE_A")) {
if (xmlObject.getIdentifiers() != null
&& !xmlObject.getIdentifiers().isEmpty()
&& xmlObject.getIdentifiers().get(0) != null) {
String mainId = xmlObject.getIdentifiers().get(0).toLowerCase();
if (xmlObject.getXmlSubObjects() != null) {
for (XmlSubObject subObject : xmlObject.getXmlSubObjects()) {
if (subObject != null && subObject.getLocation() != null) {
mapOtherStuff(subObject);
}
}
}
}
} else {
if (xmlObject.getIdentifiers() != null
&& !xmlObject.getIdentifiers().isEmpty()
&& xmlObject.getIdentifiers().get(0) != null) {
String mainId = xmlObject.getIdentifiers().get(0).toUpperCase();
}
}
}
}
}
Solution 2: Do the null checks in an inner class and store the result in those variables. Which I like but not sure if memory wise it's a smart thing to do...
The inner helper class:
static class Helper {
String type = null;
String mainId = null;
public Helper(XmlObject xmlObject) {
if (xmlObject != null) {
// Common
if (xmlObject.getName() != null) {
type = xmlObject.getName();
// Specific mapping
if (xmlObject.getIdentifiers() != null && !xmlObject.getIdentifiers().isEmpty() && xmlObject.getIdentifiers().get(0) != null) {
if (type.equals("TYPE_A")) {
mainId = xmlObject.getIdentifiers().get(0).toLowerCase();
} else {
mainId = xmlObject.getIdentifiers().get(0).toUpperCase();
}
}
}
}
}
And the previous class using the helper:
public void mapSpecificField(XmlObject xmlObject) {
Helper helper = new Helper(xmlObject);
String mainId = helper.mainId;
if ("TYPE_A".equals(helper.type)) {
if (xmlObject.getXmlSubObjects() != null) {
for (XmlSubObject subObject : xmlObject.getXmlSubObjects()) {
if (subObject != null && subObject.getLocation() != null) {
mapOtherStuff(subObject);
}
}
}
}
}
Or if anyone has a Solution 3, I'd be up for it as I really need some opinions...
Please do note that my original class has about 8 different types & lots of fields to map and I'm splitting the mapping into few methods that sometimes need the same variables. I can't share it here as it's pretty long but the classes above show exactly what it looks like.