1

I have a condition like this:

if (someObject != null)
    {
        templateUri = someObject .getSettingsObject() != null
                ? someObject .getSettingsObject().getPlanUri() : null;
    }

Instead of using multiple null checks, can I club this conditions into a single statement and run my code without getting NULL pointer Exception?

Odin
  • 580
  • 11
  • 24
  • 2
    Use `Optional` for your `SettingsObject` and `PlanUri`. https://docs.oracle.com/javase/8/docs/api/java/util/Optional.html – nbokmans May 29 '17 at 07:25

2 Answers2

0

It would be better create a method to handle the case but with a single statement you could do this:

templateUri = (someObject != null) ? (someObject.getSettingsObject()!=null ? someObject.getSettingsObject().getPlanUri() : null ) : templateUri;

If someObject is null templateUri will be replaced with itself.

Luca Montagnoli
  • 302
  • 1
  • 9
0

You can use with nested conditional operator ( ? : )

templateUri = someObject == null ? null 
                   : someObject .getSettingsObject() == null ? null 
                   : someObject .getSettingsObject().getPlanUri();
Viet
  • 3,349
  • 1
  • 16
  • 35