mardi 15 novembre 2022

Replacing If Else Statement [closed]

I am facing a problem where there are too many if conditions and also multiple return statements. When I write the code like this, it becomes a very difficult code to read. My goal is to get rid of if else statements as much as possible and to finish the code in one place.

Below I will try to explain the problem I am having with a code example.

Let's consider a code where too many external services are called and a response check must be made for each service. For Example:

public class Response{
         private Header header;
         private Body body;
    
         //get set methods
    
    }
    
    

Execute method in service class:

    public Response run(Request request){
    
       
       //Some implementation for external services request
    
       ResponseExternalService responseExternal = callExternalService(externalServiceRequest);
       if(!responseExternal.getHeader().isSuccess()){ //I have to control external service response
          response.setResponseHeader(responseExternal.getHeader());
          return response; //I have to finish flow here
       }
    
       if(Objects.nonNull(responseExternal.getBody() && Objects.nonNull(responseExternal.getBody().getExampleField())){
         ExampleField exampleField = responseExternal.getBody().getExampleField();
       }
    
    
       //continue process
     
       ResponseExternalService2 responseExternal2 = callExternalService2(externalServiceRequest2);
       if(!responseExternal2.getHeader().isSuccess()){ //I have to control external service response
          response.setResponseHeader(responseExternal2.getHeader());
          return response; //I have to finish flow here
       }
    
    
      if(Objects.nonNull(responseExternal2.getBody() && Objects.nonNull(responseExternal2.getBody().getExampleField())){
         ExampleField2 exampleField2 = responseExternal2.getBody().getExampleField();
       }
    
    
       
       //I have many conditions like this

   }

I inspected this topic: Replacing if else statement with pattern

This solution couldn't resolve my problem. This solution solve if else statements but I think it didn't solve finish flow problems.

I am looking for a solution method that solves both problems.

Aucun commentaire:

Enregistrer un commentaire