We currently have the following compound if statement...
if ((billingRemoteService == null)
|| billingRemoteService.getServiceHeader() == null
|| !\"
You can avoid both try/catch and compound ifs when using Java 8 optionals:
import java.util.List;
import java.util.Optional;
public class Optionals
{
interface BillingRemoteService
{Optional getServiceBody();}
interface ServiceBody
{Optional getServiceResponse();}
interface ServiceResponse
{Optional> getCustomersList();}
interface Customer
{Optional getBillAccountInfo();}
interface BillAccountInfo
{Optional getEcpdId();}
interface EcpId
{Optional getEcpdId();}
Object test(BillingRemoteService billingRemoteService) throws Exception
{
return
billingRemoteService.getServiceBody()
.flatMap(ServiceBody::getServiceResponse)
.flatMap(ServiceResponse::getCustomersList)
.map(l->l.get(0))
.flatMap(Optional::ofNullable)
.flatMap(Customer::getBillAccountInfo)
.flatMap(BillAccountInfo::getEcpdId).orElseThrow(()->new Exception("Failed to get information for Account Number "));
}
}
This requires you to change the signature of those methods but if they often return null this should be done anyways in my opinion. If null is not expected but an exception, and changing the method signature is not possible then exceptions can be used. I don't think the runtime difference is a problem unless you call this operation hundreds of thousands of times per second.