samedi 5 mars 2022

Remove Independent If Conditions

I have below code structure to refactor :

      @Builder
      @Value
      class ReasonAndAction {
        String reason;
        String action;
        }
        
        
        ReasonAndAction decideReasonAndAction(Input input) {
        
        if(condition1(input)) {
         return reactionAndAction1;
        }
        
        if(condition2(input)) {
         return reactionAndAction2;
        }
        
        if(condition3(input)) {
         return reactionAndAction3;
        }
        
        return ReasonAndAction.builder()
               .reason("default")
               .action("default")
               .build();
        
        }

All the if conditions are independent and may have some default behavior (else case). There may be need to add more if conditions with next versions which will make code bit ugly . What java design pattern can be used here for meaningful abstraction such that default behavior is also maintained ? Can somebody please explain with example/pseudocode ?

Aucun commentaire:

Enregistrer un commentaire