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;
}
}
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.
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.
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.
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.
I think you have 3 main options:
If you are using googles Guava libraries you can also use the Optional class.
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