Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a simpler way to derefence nullable references in Java?

Consider the following Code Snippet:

if (foo != null
 && foo.bar != null
 && foo.bar.boo != null
 && foo.bar.boo.far != null)
{
    doSomething (foo.bar.boo.far);
}

My question is simple: is there a more simple\shorter way to do this ?

In detail: is there a more simple way to validate each part of the chain, I'd imagine similar to this ..

if (validate("foo.bar.boo.far"))
{
    doSomething (foo.bar.boo.far);
}
like image 728
Khaled.K Avatar asked Jan 14 '23 08:01

Khaled.K


2 Answers

Maybe like that ?

if (FooUtils.isFarNotEmpty(foo)){
    doSomething (foo.bar.boo.far);
}

and in FooUtils :

boolean isFarNotEmpty (Foo foo){
   return foo != null && 
          foo.bar != null && 
          foo.bar.boo != null && 
          foo.bar.boo.far != null;
}
like image 133
Grisha Weintraub Avatar answered Feb 02 '23 19:02

Grisha Weintraub


In my opinion this expression is perfect, nothing can be simpler

like image 25
Evgeniy Dorofeev Avatar answered Feb 02 '23 20:02

Evgeniy Dorofeev