Skip to content

Instantly share code, notes, and snippets.

@neoneo40
Last active December 1, 2015 07:48
Show Gist options
  • Save neoneo40/e6e09b6b15ed1778a911 to your computer and use it in GitHub Desktop.
Save neoneo40/e6e09b6b15ed1778a911 to your computer and use it in GitHub Desktop.
Refactoring question

Refactoring question

Extract Method

  • p.146
  • 책에서는 계속 임시 변수 사용을 줄이라고 하는데 왜 임시변수 사용을 줄여야 하는가?
  • 내가 보기에는 outstanding 이라는 임시변수를 만들어 놓으면 outstanding 임시변수만 수정하게 되면 편하게 get_outstanding의 매개변수를 변경할 수 있어서 편한다고 생각이 들고 이게 좀 더 소스코드를 읽기 좋다고 생각한다.
  • 책에서 말하는 refactoring을 하면 get_outstanding의 파라미터를 변경하려면 keyboard 키를 몇 번 더 움직여야 하고 직관적이지 못하다.
def print_owing_with_no_refactoring(previous_amount):
    outstanding = previous_amount * 1.2
    print_banner()
    outstanding = get_outstanding(outstanding)
    print_details(outstanding)
    
def print_owing_with_refactoring(previous_amount):
    print_banner()
    outstanding = get_outstanding(previous_amount * 1.2)
    print_details(outstanding)

Replace Temp with Query

  • p.153
  • 여기에서도 임시 변수를 메소드로 변경하라고 하는데 왜 굳이 메소드로 변경하는가?
    • 책의 설명에 따르면 메소드로 만들면 범용적으로 다른 클래스나 다른 모듈에서 호출할 수 있기 때문에 더 좋다고 한다. 왠만한 임시변수들은 메소드로 바꾸라고 한다. 내 생각에도 맞는것 같은데 같은 계산을 몇 번씩 할 필요가 있을까?
  • base_price를 한 번만 하면 되잖아? 근데 책에서 설명하는 방식으로 하면 base_price를 구하려고 함수를 총 3번을 부른다. 그럼 속도가 더 느려지지않나?
  • 그래서 내가 생각한 최선의 방법은 base_price()를 한 번 부르고 임시변수에 할당하고 그걸 계속 쓰는 것이다.
##
def price_with_temp_variable():
    base_price = _quantity * _item_price
    if base_price > 1000:
        return base_price * 0.95
    else:
        return base_price * 0.98

##
def base_price_with_temp_method():
    if base_price() > 1000:
        return base_price() * 0.95
    else:
        return base_price() * 0.98
    
def base_price():
    return _quantity * _item_price

##
def base_price_with_temp_method_i_think():
    base_price = base_price()
    if base_price > 1000:
        return base_price * 0.95
    else:
        return base_price * 0.98
    
def base_price():
    return _quantity * _item_price

Replace Temp with Query2

  • p.155
  • 여기에서 임시변수를 왜 쓰지 말아야 하는지 제대로 설명을 해주는 것 같은데..?
def get_price():
    base_price = _quantity * _item_price
    if base_price > 1000:
        discount_factor = 0.95
    else:
        discount_factor = 0.98
    return base_price * discount_factor
  • 두 임시변수를 한 번에 하나씩 메소드 호출로 바꿔보자.
  • 임시변수를 한 번에 하나씩 메서드 호출로 바꾸자. 우선 대입문의 우변을 다음과 같이 메서드로 빼내자.
def get_price():
    base_price = get_base_price()
    if base_price > 1000:
        discount_factor = 0.95
    else:
        discount_factor = 0.98
    return base_price * discount_factor

def get_base_price():
    return _quantity * _item_price
  • 컴파일과 테스트를 실시한 후 임시변수 내용 직접 삽입을 실시하자. 우선 다음과 같이 첫번째 임시변수 참조 부분을 교체하자
def get_price():
    base_price = get_base_price()
    if get_base_price() > 1000:
        discount_factor = 0.95
    else:
        discount_factor = 0.98
    return base_price * discount_factor
  • 컴파일과 테스트를 실시하고 두 번째 임시변수 참조 부분을 바꿀 차례다. 이후엔 더 이상 임시 변수 참조 부분이 없으니 임시변수 선언도 삭제하자.
def get_price():
    if get_base_price() > 1000:
        discount_factor = 0.95
    else:
        discount_factor = 0.98
    return get_base_price() * discount_factor
  • 앞의 코드처럼 고쳤으면 앞에서처럼 discount_factor 메소드로 빼내자
def get_price():
    discount_factor = discount_factor()
    return get_base_price() * discount_factor()

def discount_factor():
    if get_base_price() > 1000:
        return 0.95
    else:
        return 0.98
  • base_price 임시변수를 메소드 호출로 바꾸지 않았다면 discount_factor 메소드로 빼내기가 매우 힘들었을 것
  • 최종적인 get_price 메소드의 모습은 다음과 같다.
def get_price():
    return get_base_price() * discount_factor()

소스 코드 Before After

# Before
def get_price():
    base_price = _quantity * _item_price
    if base_price > 1000:
        return base_price * 0.95
    else:
        return base_price * 0.98

# After
def get_base_price():
    return _quantity * _item_price

def discount_factor():
    if get_base_price() > 1000:
        return 0.95
    else:
        return 0.98

def get_price():
    return get_base_price() * discount_factor()

최종 결론?

  • 비록 똑같은 연산을 여러번 하더라도 메소드로 만들어서 빼내고 여러번 호출하는게 낫다? 라는게 결론인듯..??
  • 6줄 -> 9줄로 되었지만 get_price() 함수가 굉장히 간단해졌다. 모두 메서드로 추출해 버리니 소스코드 독해력이 높아졌다. base_price * discount_factor.
  • 그리고 base_price를 다른 함수나 모듈에서도 호출할 수 있기 때문에 좀 더 유연해진 것 같다.
  • 백종만님 답변을 읽고 또 여러번 훑어본 결과 이해가 됨..
@neoneo40
Copy link
Author

neoneo40 commented Dec 1, 2015

디버깅 할 때는 어떻게 하나?

  • 임시변수를 모두 삭제하고 함수로 만든다면 함수를 호출한 다음 결과값이 임시변수로 들어가야 내가 함수를 호출한 결과값이 뭐다 라고 알 수 있을텐데 모두 함수로 만들어 놓으면 결과값이 메모리에만 저장되어 있기 때문에 내 눈에는 보이지 않나??
  • 그래서 어쩔 수 없이 임시 변수를 하나 만들어서 내 결과값이 맞는지 확인하는 결과를 거쳐야 할 것 같은데??

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment