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?
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")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With