0

Is there an elegant way to check if a string of fields is null?

Let's say I have:

String fieldD = myString.getFieldA().getFieldB().getFieldC().getFieldD();

I could do something like

String fieldD = null;
if (myString.getFieldA() != null
        && myString.getFieldA().getFieldB() != null
        && myString.getFieldA().getFieldB().getFieldC() != null) {
    String fieldD = myString.getFieldA().getFieldB().getFieldC().getFieldD();
}

or I could do something like

String fieldD = null;
try {
    String fieldD = myString.getFieldA().getFieldB().getFieldC().getFieldD();
} catch (NullPointerException e) {
    // do nothing
}

But there has to be a more elegant solution than either of these right? I'm sure this is already answered somewhere, but I can't seem to find it.

Azianese
  • 554
  • 7
  • 21
  • 3
    There doesn't actually have to be a more elegant solution. – Louis Wasserman Jun 28 '21 at 19:46
  • 1
    By which he means: There isn't. – Andreas Jun 28 '21 at 19:52
  • Welp, guess I'll go with the second option in my post and have catch clauses everywhere then. I was hoping for a simple one-liner since I currently have many fields which need to be checked back-to-back. Kind of gross to look at, but guess it can't be avoided :/ – Azianese Jun 28 '21 at 19:53
  • 2
    Often the best solution is to write those methods so they cannot return null. Under no circumstances should anyone catch NullPointerException, as that class exists to expose programmer mistakes. – VGR Jun 28 '21 at 19:54
  • That was one of the reasons they invented Optionals. Check the following article https://www.oracle.com/technical-resources/articles/java/java8-optional.html – Panagiotis Bougioukos Jun 28 '21 at 19:57
  • Well, of course, one could use `Optional`: `Optional.ofNullable(myString).map(a -> a.getFieldA()).map(b -> b.getFieldB()).map(c -> c.getFieldC()).map(d -> d.getFieldD()).ifPresent(result -> ...)`. – MC Emperor Jun 28 '21 at 19:58
  • Thanks for the suggestions and resources! I'll make sure to not go with the second option in my post and look into alternatives like Optionals – Azianese Jun 28 '21 at 20:01

0 Answers0