Extract Function - Refactoring skills(1)

Kerem Song·2021년 3월 23일
0

Refactoring - Study

목록 보기
3/22

1. Extract Function(함수 추출하기)

Extract fragment of code into its own function named after its purpose.
코드 조각을 찾아 무슨 일을 하는지 파악 후, 독립된 함수로 추출하고 목적에 맞는 이름 붙이기

function printOwing(invoice) {
  printBanner()
  let outstannding = calculateOutstanding()

  // print details
  console.log(`name: ${invoice.customer}`)
  console.log(`amount: ${outstanding}`)
}

to

function printOwing(invoice) {
  printBanner()
  let outstannding = calculateOutstanding()
  printDetails(outstanding)

  function printDetails(outstanding) {
    console.log(`name: ${invoice.customer}`)
    console.log(`amount: ${outstanding}`)
  }
}

Motivation

  1. You know what's the code doing without reading the details
    (부연 설명 없이 코드가 무슨 일을 하는지 알 수 있음)
  2. Short function is easier to read
    (짧은 함수는 읽기 쉬움)
  3. Reduce comment
    (설명, 주석을 줄일 수 있음)

Procedure(절차)

  1. Make a new function and give a name which is nice to reveal the purpose.
    함수를 새로 만들고 목적을 잘 드러내는 이름을 붙인다.('어떻게'가 아닌 '무엇을' 하는지가 드러나야 한다.)

  2. Copy the code what you want to extract, and add to new function.
    추출할 코드를 원본 함수에서 복사하여 새 함수에 붙여넣는다.

  3. We examine whether any extracted code refers to the local variable of the original function or is outside the effective range of the extracted function. If so, pass it to the parameters.
    추출한 코드 중 원본 함수의 지역 변수를 참조하거나 추출한 함수의 유효범위를 벗어나는 변수는 없는지 검사한다. 있다면 매개변수로 전달한다.

  4. Compile the variables when they are completely processed.
    변수를 다 처리했으면 컴파일한다.

  5. Replace the part of the code extracted from the original function with a statement calling the newly created function (i.e., delegating things to the extracted function).
    원본 함수에서 추출한 코드 부분을 새로 만든 함수를 호출하는 문장으로 바꾼다(즉, 추출한 함수로 일을 위임한다.

  6. Test it.
    테스트

  7. Check the other codes for the same or similar codes that you extracted.
    If you have, consider replacing the new function you just extracted with a function call. (Replace the inline code with a function call)
    다른 코드에 방금 추출한 것과 똑같거나 비슷한 코드가 없는지 살핀다. 있다면 방금 추출한 새 함수를 호출하도록 바꿀지 검토한다.(인라인 코드를 함수 호출로 바꾸기)

profile
Tea and Dessert

0개의 댓글