ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • 얼리 리턴 패턴(Early Return Pattern) 이란?
    클린 코드(Clean Code) 2022. 2. 6. 00:01
    728x90

    얼리 리턴 패턴이란?

    함수나 메서드를 작성하는 패턴으로, 예상되는 긍정 결과가 함수의 끝에서 리턴되게 하고 조건이 맞지 않는 경우 나머지 코드는 반환하여 실행을 종료합니다.

     

     

    Ealry Return 말 그대로 리턴을 일찍하여 뒷 코드의 구조를 단순하게 만들어주는 패턴으로 else를 제거하는 것이 목적입니다.

     

    코드를 통하여 더 알아보겠습니다.

     

    Early Return 패턴 적용 전

    public String returnStuff(SomeObject argument, SomeObject argument2){
    	if(argument1.isValide()){
            if(argument2.isValide()){
            	SomeObject otherVal1 = doSomeStuff(argument1, argument2)
                
                if(otherVal1.isValid()){
                	someObject otherVal2 = doAnothreStuff(otherVal1)
                    
                    if(otherVal2.isValide()){
                    	return "Stuff";
                     }else{
                     	throw new Exception();
                     }
                }else{
                	throw new Exception();
                }
            }else{
            	throw new Exception();
            }
        }else{
        	throw new Exceptioon();
        }
    }

    if-else문이 중첩되어 있기 때문에 가독성이 좋지 않고 부드럽게 읽히지 않습니다.

    계속 조건을 기억하고 있어야 하며 else가 어떤 if와 맞는지도 계속하여 비교해야 합니다.

    또한 indentation이 화살모양처럼 되어 여러번 발생하게 됩니다.

     

    Ealry Return 패턴 적용 후

    public String returnStuff(SomeObject argument1, SomeObject argument2){
    	if(!argument1.isValid()) {
    		throw new Exception();
    	}
        
    	if(!argument2.isValid()) {
    		throw new Exception();
    	}
        
    	SomeObject otherVal1 = doSomeStuff(argument1, argument2);
        
    	if(!otherVal1.isValid()) {
    		throw new Exception();
    	}
        
    	SomeObject otherVal2 = doAnotherStuff(otherVal1);
        
    	if(!otherVal2.isValid()) {
    		throw new Exception();
    	}
        
    	return "Stuff";
    }

     

     

    위의 코드는 indentation이 1번만 있습니다.

    따라서 가독성이 좋아지고 예상되는 긍정 결과는 함수에 끝에서 빠르게 찾을 수 있습니다.

    에러를 먼저 잡고 그 다음 불필요한 버그를 피하면서 안전하게 비즈니스 로직을 구현할 수 있습니다.

    함수가 에러 발생시 즉시 종료되기 때문에 의도되지 않은 코드가 실행될 가능성을 피할 수 있습니다.

     

    그러면 항상 이런 패턴이 옳을까요?

    public String returnStuff(SomeObject argument) {
      if(!argument.isValid()) {
        return;
      }
      
      return "Stuff";
    }
    
    public String doStuff(SomeObject argument) {
      if(argument.isValid()) {
        return "Stuff";
      }
    }

    첫 번째 방식은 얼리 패턴 방식을 적용하였지만 두 번째 방식에 비해 작성된 코드도 많고 복합해 보입니다.

    이런 경우에는 두 번째 방식을 사용하다가 나중에 얼리 패턴 방식이 필요할 때 변경하면 좋습니다.

     

     

    출처

     

    https://medium.com/swlh/return-early-pattern-3d18a41bba8

     

    Return Early Pattern

    A rule that will make your code more readable.

    medium.com

     

    댓글

Designed by Tistory.