-1

I have something like this:

   request.getData().getPerson().getAddress().getZipcode()

I am looking for efficient way to do the null check but don't want to add many if's . I have similar thing in many places and looking for the best way to address this.

Thanks in advance.

Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724
FigureCodeOut
  • 79
  • 1
  • 11
  • 1
    This `request.getData().getPerson().getAddress().getZipcode()` is a code smell in and of itself. – Fildor Feb 01 '23 at 16:02
  • Please see message chains in code smell and also Law of Demeter for programming. – Tia Feb 01 '23 at 16:07

1 Answers1

3

You can use Optional.

Optional.ofNullable(request).map(x -> x.getData()).map(x -> x.getPerson())
        .map(x -> x.getAddress()).map(x -> x.getZipcode()).orElse(null);
Unmitigated
  • 76,500
  • 11
  • 62
  • 80