0

I have one complex object just like this;

Object A
   Object B
    Object C
      Object D
        property A
        property B

So If I need to show the property A in my view, I need to

  A.getB().getC().getD().getPropertyA();

but what if my user doesn`t send the object C?

so I need to create one If for every object

if(A.getB() != null){
  if(A.getB().getC() != null){
    if(A.getB().getC().getD() != null){
      //here I can show the propertyA
    }
  } 
}

now I have to show this property in 3 views

There is a better way to does this? a framework or something like this to solve this problem?

Andronicus
  • 25,419
  • 17
  • 47
  • 88
Fabio Ebner
  • 2,613
  • 16
  • 50
  • 77
  • 2
    Does this answer your question? [Avoiding != null statements](https://stackoverflow.com/questions/271526/avoiding-null-statements) – OH GOD SPIDERS Feb 26 '20 at 17:13

1 Answers1

3

You can use Optional.ofNullable and map:

Optional.ofNullable(A.GetB())
    .map(B::getC)
    .map(C::getD)
    .map(D::getPropertyA)
    .orElseThrow()

P.S.1: Some developers (and linters) find this approach a code smell, but I think it's more readable that way.

P.S.2: You can use a default value with .orElse instead of .orElseThrow.

Andronicus
  • 25,419
  • 17
  • 47
  • 88