Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to code NullPointerException safe method and expressions?

NullPointerException is always a code clutterer. Need to check if every object is null safe and don't throw NPE.

I came across a situation:

 public void aMethod(Employee emp){
     String fullEmployeeDetailRow = "Name: "+emp.getName().getFirstName()
     +"LastName :"+emp.getName().getFirstName()
    +"Address:"
  +emp.getAddress().getBillingAddress().getBuildingNumber().getApartmentNumber()
  +" "    
  +emp.getAddress().getBillingAddress().getStreetName()
  }

In above example there are so many possibilities of NPE. For instance in

emp.getAddress().getBillingAddress().getBuildingNumber().getApartmentNumber() 

expression, call to

getAddress() or getBillingAddress() or getBuildingNumber() 

any can be null and probable NPE source. So I now need to clutter my code to check if each can be null.

My Question / Thought is: is there a way in Java to CREATE a method which takes an expression and evaluate if it throws NullPointerException and if yes then return a default value, say a blank " "?

So in this case I need a method

expression=emp.getAddress().getBillingAddress().getBuildingNumber().getApartmentNumber()

String checkForNPE(expression){
    try{
      return expression;
      }catch(NullPointerException e){
         return " "   // default Value
      }
    }

Problem is when I try to create a method like this , and pass an expression to it, Java evaluates the expression BEFORE calling the method and NPE is thrown beforehand!

How can I pass the expression to the method and ask Java to evaluate it inside method only?

like image 266
supernova Avatar asked Jan 07 '23 06:01

supernova


1 Answers

You can use Optional in this situation.

Option.ofNullable(emp)
      .map(e -> e.getAddress())
      .map(a -> a.getBillingAddress())
      .map(a -> a.getBuildingNumber())
      .map(n -> n.getApartmentNumber())
      .orElse("not set")
like image 106
Peter Lawrey Avatar answered Mar 03 '23 23:03

Peter Lawrey