상세 컨텐츠

본문 제목

6.1. 함수 추출하기

🍜개발자라면/책을 읽자✍

by :Eundms 2021. 9. 26. 13:13

본문

- 목적/구현을 분리하기 위해 함수로 만들기 

highlight()함수 내에 reverse()라는 메서드만 호출 : 길이는 중요하지 않음.


방법

1. 함수를 새로 만들고 목적을 잘 드러내는 이름을 붙인다. ('어떻게'가 아닌 '무엇을 하는지'가 드러나야 한다)

-> 목적이 드러나는 이름, 중첩 함수를 지원하는 언어를 사용한다면 추출한 함수를 원래 함수 안에 중첩, 언제든 함수 옮기기를 적용.

2. 추출할 코드를 원본 함수에서 복사하여 새 함수에 붙여넣는다.

3. 추출한 코드 중 원본 함수의 지역 변수를 참조하거나 추출한 함수의 유효범위를 벗어나는 변수는 없는지 검사한다. 있다면 매개변수로 전달한다.

4. 변수를 다 처리했다면 컴파일한다.

5. 원본 함수에서 추출한 코드 부분을 새로 만든 함수를 호출하는 문장으로 바꾼다. (즉, 추출하나 함수로 일을 위임한다.)

6. 테스트한다.

7. 다른 코드에 방금 추출한것과 똑같거나 비슷한 코드가 없는지 살핀다. 있다면 방금추출한 새 함수를 호출하도록 바꿀지 검토한다.

 

 


  지역 변수를 사용할 때  

지역 변수들을 매개변수로 넘기면 된다.
// 변경 이전 코드
function printOwing(invoice){
    let outstanding=0;
    printBanner();
    for (const o of invoice.orders){
      outstanding+=o.amount;
    }
    const today = Clock.today;
    invoice.dueDate = new Date(today.getFullYear(),today.getMonth(),today.getDate()+30);
    console.log(`고객명 :${invoice.customer}`);
    console.log(`채무액 :${outstanding}`);
    console.log(`마감일 : ${invoice.dueDate.toLocaleDateString()}`);
}

// 변경 후
function printOwing(invoice){

    let outstanding = 0;
    printBanner();
    for (const o of invoice.orders){
        outstanding+=o.amount;
    }
    // 지역변수가 데이터 구조라면 똑같이 매개변수로 넘긴 후 필드 값을 수정
    recordDueDate(invoice);
    // 지역변수를 매개변수로 전달
    printDetails(invoice,outstanding);
    
}
function recordDueDate(invoice){
    const today = Clock.today;
    invoice.dueDate = new Date(today.getFullYear(), today.getMonth(), today.getDate()+30);
}
function printDetails(invoice,outstanding){
    console.log(`고객명 :${invoice.customer}`);
    console.log(`채무액 :${outstanding}`);
    console.log(`마감일 : ${invoice.dueDate.toLocaleDateString()}`);
}

  지역 변수의 값을 변경할 때  

매개변수에 값을 대입하는 코드를 발견하면,
임시 변수를 새로 하나 만들어 변수에 대입하도록 한다.
// 1) let outstanding = 0;을 관련 있는 코드 근처로 옮긴다.
function printOwing(invoice){
    printBanner();
    
    let outstanding = 0;
    for (const o of invoice.orders){
        outstanding+=o.amount;
    }
    recordDueDate(invoice);
    printDetails(invoice,outstanding);
}

// 2) 추출할 코드 복사
function printOwing(invoice){
    printBanner();
    
    let outstanding = 0;
    for (const o of invoice.orders){
        outstanding+=o.amount;
    }
    recordDueDate(invoice);
    printDetails(invoice,outstanding);
}
function calculateOutstanding(invoice){
    let outstanding = 0; 
    for (const o of invoice.orders){
        outstanding += o.amount;
    }
    return outstanding; 
}

// 3) 새로운 함수 호출 및 반환값 저장
function printOwing(invoice){
    printBanner();
    const outstanding = calculateOutstanding(invoice);
    recordDueDate(invoice);
    printDetails(invoice,outstanding);
}
function calculateOutstanding(invoice){
    let outstanding = 0; 
    for (const o of invoice.orders){
        outstanding += o.amount;
    }
    return outstanding; 
}

// 4) 코딩스타일 변경
function printOwing(invoice){
    printBanner();
    const outstanding = calculateOutstanding(invoice);
    recordDueDate(invoice);
    printDetails(invoice,outstanding);
}
function calculateOutstanding(invoice){
    let result = 0; 
    for (const o of invoice.orders){
        result += o.amount;
    }
    return result; 
}

 값을 반환할 변수가 여러 개라면? 

레코드로 묶어서반환 : 임시 변수를 질의함수로 바꾸거나, 변수를 쪼개는 식으로 처리
원본 함수와 같은 수준의 문맥으로 먼저 추출해보자

 

관련글 더보기

댓글 영역