Is there an easier way to eliminate null 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 simpler / shorter way to do this?

In detail: is there an easier way to check every part of the chain, I would suggest that it looks like this.

 if (validate("foo.bar.boo.far")) { doSomething (foo.bar.boo.far); } 
+4
source share
6 answers

Maybe so?

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

and FooUtils :

 boolean isFarNotEmpty (Foo foo){ return foo != null && foo.bar != null && foo.bar.boo != null && foo.bar.boo.far != null; } 
+5
source

In my opinion, this expression is perfect, nothing could be easier

+2
source

why you use an open instance variable, encapsulate your public variables and create getter and setter for them, and you can do this check in your getter, and you can return a new Object () if any of them is null, or you can run this statement in a try-catch block, but not recommended

+1
source

If this is your API, please consider some recommendations .

"I call it my billion dollar mistake." - Sir K. A. R. Hoar, on his invention of zero reference

+1
source

Unfortunately, you cannot handle this. If you ask me, this is a problem with the Java language. Does Groovy have something called Safe Navigation Operator? that is specifically designed for this purpose. Here are two things I've done in the past.

  • The answer that Grisha has already given, so I will not repeat it
  • Naive code that accesses it and surrounds it in try / catch for NPE. Here is an example:

     try { if (foo.bar.boo.far != null) { //do something } } catch (NullPointerException e) { //do what you would do in an else } 

I don't like the second option, but I say if it really makes the code cleaner, consider using it.

I once worked with a library, which is a very thin shell on an XML schema, and I decided to use the second option for this case. If I hadn’t done this, the code would have been harder to maintain, because it would have been easy to forget the null check, and they cluttered the important logic. I think this is a valid case for using it.

0
source

Please try this code.

 try { if (foo.bar.boo.far != null) { //No object is null } } catch (Exception e) { // some object is null and causes null point exception. } 
0
source

Source: https://habr.com/ru/post/1481880/


All Articles