0

I'm looking to populate an object with some values from a complex xml object. To get to the right value i have to get through a big chain of elements and i have to check them all to not be null. So my code will look like this X 9 times. I don't want to stop the populate process just because one element is missing, I want to 'skip' the null pointer somehow and get to the next propriety. My only idea is to put every line in a try/catch block. Got any better ideas? Thanks

objModel.setProviderHeadquarterName(obj.getObject("YYY") != null && obj.getObject("YYY").getArray("gob") != null && obj.getObject("YYY").getArray("gob").size() > 0 && obj.getObject("YYY").getArray("gob") != null ? obj.getObject("YYY").getArray("gob").getObject(0).getString("gobValue") : "");
objModel.setProviderHeadquarterName(obj.getObject("XXX") != null && obj.getObject("XXX").getArray("tem") != null && obj.getObject("XXX").getArray("tem").size() > 0 && obj.getObject("XXX").getArray("tem") != null ? obj.getObject("XXX").getArray("tem").getObject(0).getString("temValue") : "");
objModel.setProviderHeadquarterName(obj.getObject("ZZZ") != null && obj.getObject("ZZZ").getArray("has") != null && obj.getObject("ZZZ").getArray("has").size() > 0 && obj.getObject("ZZZ").getArray("has") != null ? obj.getObject("ZZZ").getArray("has").getObject(0).getString("hasValue") : "");

How can

radu
  • 7
  • 4
  • 3
    Don't write that code. If your XML object can't tolerate nulls, don't allow them to be added to the collection. XML is a hierarchical data representation, so recursion should be your friend. – duffymo Oct 04 '17 at 11:59
  • Possible duplicate of https://stackoverflow.com/questions/271526/avoiding-null-statements. – VGR Oct 04 '17 at 12:06

2 Answers2

4

You can wrap this in an Optional and deal with the nulls implicitly:

Optional.of(obj).map(o -> o.getObject("YYY")).map(o -> o.getArray("gob")) /* [snip] */
        .orElse(""); //etc
Joe C
  • 15,324
  • 8
  • 38
  • 50
0

To answer your question literally, you could extract that in a separate method and catch the potential exceptions. But that's not best practice:

private static Object getValueOrNull(Supplier<Object> s) {
  try {
    return s.get();
  } catch (Exception e) { //narrow down the exception if possible
    return null;
  }
}

Which you can call like this (the value may be null):

Object value = getValueOrNull(() -> obj.getObject("YYY").getArray("gob").getObject(0).getString("gobValue"));
assylias
  • 321,522
  • 82
  • 660
  • 783
  • I would really only catch the NPE in this case. Easy to swallow other exceptions that we actually need to handle. – Joe C Oct 04 '17 at 13:37
  • @JoeC I think the code may also throw ArrayIndexOutOfBoundsException. So I kept it wide and put a comment in the code saying that the exception type should be narrowed down if possible. – assylias Oct 04 '17 at 14:11