본문 바로가기

내직업은 IT종사자/javascript

ealry return 은 좋은 것일까?

반응형

 

 

Early Return 패턴

코드를 작성할 때 기능에 따라 여러 조건문을  사용하게 되는데  그때마다  어떻게 하면 가독성 높게 코드를 짤 수 있을까 고민하게 됩니다 (매번... 너무어려워 ㅠㅠ)

그 중에  Early Return패턴을 종종 사용하게되는데 문득  early return 을 사용하는 것이 좋을까? 안좋을까? 라는 고민을 하게 되었습니다.

 

 

1. Early Return 이란?


 

Early Return은 함수에서 조건문을 만족할 때 일찍 반환하는 것을 의미합니다.

 

 

2. Early Return 의 장단점


 

2-1. 장점

- early return은 들여쓰기  즉  중첩 조건문을 줄여 코드를 간결하고 읽기 쉽게 만들어 줍니다.

- 코드의 비선형적인 흐름을 선형으로 바꾸어 주어 가독성을 높혀줍니다

- 조건이 추가 되어야한다면 그만큼 depth 도 깊어지고 복잡해지는데 이를 방지해 줍니다.

 

[AS-IS]

if someCondition {
    if someOtherCondition {
        if someOtherOtherCondition {
            // do something
        }
    }
}

 

 

[TO-BE]

if someCondition {
    return
}
// do something
if someOtherCondition {
    return
}
// do something
if someOtherOtherCondition {
    return
}

 

 

2-2. Early Return 의 단점

 

함수의 반환이 여러곳으로 흩어지게 되면 함수의 복잡도를 높이고 오히려 가독성을 떨어뜨릴 수 도 있습니다

예를들어  스크롤을 많이해야할 만큼  한파일 안에 작성된 코드가 많아졌을때  그 속의 여러 함수에서 return 문이 무작위로 존재한다면 

읽기 난해할 것입니다 

(이를  해소하고 적당한 코드량을 유지하기 위해서는 bouncer Pattern이나  extract method 패턴 사용을 고려해보기! )

 

 

2-2-1.  Bouncer Pattern

 

bouncer pattern은 예외를 반환, 발생시켜 특정 조건을 확인하는 방법이다.
이는 특히 유효성 검사 코드가 복잡할 때나 muultiple scenarios에 사용하기 유용하다. 
이 패턴은 return early 패턴을 보완해준다.

 

 

function authenticateUser(user) {
  if (!user || !user.isAuthenticated) {
    throw new Error("User is not authenticated.");
  }
}

function processRequest(request, user) {
  try {
    authenticateUser(user);
    // 요청 처리 로직
    console.log("Request processed successfully.");
  } catch (error) {
    console.error("Error processing request:", error.message);
  }
}

// 사용자가 인증되어 있지 않은 경우
const unauthenticatedUser = { isAuthenticated: false };
processRequest("Some request", unauthenticatedUser);

// 사용자가 인증된 경우
const authenticatedUser = { isAuthenticated: true };
processRequest("Another request", authenticatedUser);

 

 

 

2-2-2.  extract method pattern

 

코드의 일부분이 반복되거나 코드 블록이 너무 길어지면 해당 부분을 별도의 함수로 추출할 때 사용하는 패턴입니다

이를 통해 코드를 더 읽기 쉽고 유지보수 하기 쉽게 만들 수 있습니다.

 

[AS-IS]

function calculateTotalPrice(products) {
  let totalPrice = 0;
  for (let i = 0; i < products.length; i++) {
    totalPrice += products[i].price;
  }
  if (totalPrice > 100) {
    console.log("Total price is greater than 100.");
  } else {
    console.log("Total price is less than or equal to 100.");
  }
  return totalPrice;
}

 

위의 코드에서는 `calculateTotalPrice` 함수가 두가지 역할을 합니다  

1. 제품가격의 총합을 계산,

2. 총합에 따라 다른 출력문 

 

위의 코드를 두개의 메소드로 분리해서 작성할 수 있습니다

 

[TO-BE]

function calculateTotalPrice(products) {
  let totalPrice = calculatePriceSum(products);
  printTotalPriceMessage(totalPrice);
  return totalPrice;
}

function calculatePriceSum(products) {
  let totalPrice = 0;
  for (let i = 0; i < products.length; i++) {
    totalPrice += products[i].price;
  }
  return totalPrice;
}

function printTotalPriceMessage(totalPrice) {
  if (totalPrice > 100) {
    console.log("Total price is greater than 100.");
  } else {
    console.log("Total price is less than or equal to 100.");
  }
}

 

 

3. 끝으로


 Early Return 은 중첩을 줄여 코드를 간결하고 읽기 쉽게 만드는 좋은 방법입니다

하지만, 이 방법이 매번 옳다고 적용해야할 패턴은 아닌 것 같습니다

때로는 Early Return 패턴이 함수의 복잡도를 증가시키고 코드를 더 복잡하게 만들 수 있습니다.

또한 간결한 코드 에서는 오히려 if-else 문이 더 명확하게 읽힐 수 있습니다

 

따라서, 읽기 쉬운 코드를 작성하기 위해서는 상황에 맞게 적절한 패턴을 선택하는 것이 중요합니다

반응형