Cost of compound if/or versus try/catch in Java 6

后端 未结 7 1656
旧时难觅i
旧时难觅i 2020-12-31 20:12

We currently have the following compound if statement...

if ((billingRemoteService == null)
    || billingRemoteService.getServiceHeader() == null
    || !\"         


        
7条回答
  •  甜味超标
    2020-12-31 20:32

    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.

提交回复
热议问题