Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A suitable pattern instead of returning nulls

What would be a good pattern to use here?

I don´t want to return nulls, that just does not feel right.

Another thing is, what if I want to return the reason that causes it to null? If caller knows why it is null, it can do some extra things so I want caller knows it and acts that way

Public CustomerDetails getCustomerDetails(){
   if(noCustomer){    
     ..log..etc..
     return null;
   }

   if(some other bad weird condition){    
     ..log..etc..
     return null;
   }

   CustomerDetails details= getCustomerDetailsFromSomewhere();

   if (details!=null){
      return details;
   }
   else {
     ..log..etc..
     return null;
   }

}
like image 635
Spring Avatar asked Dec 27 '12 10:12

Spring


People also ask

What to do instead of returning null?

Another way to avoid returning null is to use a Null object design pattern. A null object is an object without behavior like a stub that a developer can return to the caller instead of returning null value. The caller doesn't need to check the order for null value because a real but empty Order object is returned.

What can I use instead of null in Java?

Throwing an exception is another common alternative in the Java API to returning a null when, for any reason, a value can't be provided. A typical example of this is the conversion of String into an int , provided by the Integer.

Why we should not return null?

Returning null Creates More Work A function that returns a null reference achieves neither goal. Returning null is like throwing a time bomb into the software. Other code must a guard against null with if and else statements. These extra statements add more complexity to the software.

Is returning null a good practice in Java?

The rationale behind not returning null is that you do not have to check for it and hence your code does not need to follow a different path based on the return value. You might want to check out the Null Object Pattern which provides more information on this.


1 Answers

I think you have 3 main options:

  • If null is a valid state I see no problem in returning null
  • If null is an invalid state you should throw an exception
  • Or make use of the Null object pattern

If you are using googles Guava libraries you can also use the Optional class.

like image 74
micha Avatar answered Sep 23 '22 13:09

micha