본문 바로가기

반응형

개발/리팩토링

(5)
[리팩토링 2판 파이썬 코드로 변경해보기] 3탄 함수 쪼개기, 변수명 변경 리팩토링 2판의 제일 처음 나오는 예제를 파이썬 코드로 변경 하면서, 책의 내용에 따라 리팩토링 해보고 저자의 의견과 내 의견을 정리 import json import math def statement(invoice, plays): total_amount = 0 volume_credits = 0 result = f"청구 내역 (고객명: {invoice['customer']})\n" dollar_format = '${:,.2f}' for perf in invoice["performances"]: play = plays[perf["playID"]] this_amount = 0 if play["type"] == "tragedy": this_amount = 40000 if perf["audience"] > 30..
[리팩토링 2판 파이썬 코드로 변경해보기] 2탄 statement() 테스트 코드 추가 리팩토링 2판의 제일 처음 나오는 예제를 파이썬 코드로 변경 하면서, 책의 내용에 따라 리팩토링 해보고 저자의 의견과 내 의견을 정리 테스트 추가 하기 리팩토링으로 인해서, 앞으로 변경 될 코드를 검증하기 위해서 테스트를 먼저 추가 해야 만 한다. import json import unittest from refactoring.main import statement class TestStatement(unittest.TestCase): def test_statement(self): # Given: json 파일로 부터 invoice와 plays를 불러오고, with open("invoices.json") as json_file: invoice = json.load(json_file)[0] with ope..
[리팩토링 2판 파이썬 코드로 변경해보기] 1탄 기본 코드 세팅 리팩토링 2판의 제일 처음 나오는 예제를 파이썬 코드로 변경 하면서, 책의 내용에 따라 리팩토링 해보고 저자의 의견과 내 의견을 정리 책에 나오는 코드들을 파이썬으로 바꾸면 아래와 같다. # plays.json { "hamlet": {"name": "Hamlet", "type": "tragedy"}, "as-like": {"name": "As You Like It", "type": "comedy"}, "othello": {"name": "Othello", "type": "tragedy"} } #invoices.json [ { "customer": "BigCo", "performances": [ { "playID": "hamlet", "audience": 55 }, { "playID": "as-like",..
함수 인라인하기 (Inline Function) # Before def get_rating(driver): return 2 if more_than_five_late_deliveries(driver) else 1 def more_than_five_late_deliveries(driver): return 2 if driver.number_of_late_deliveries > 5 else 1 # After def get_rating(driver): return 2 if driver.number_of_late_deliveries else 1 배경 언제 적용하면 될까? 함수 본문이 이름만큼 명확할 때 인라인을 하자. 간접 호출을 너무 과하게 쓰는 것도 흔한 인라인 대상 단순히 위임하기만 하는 함수들이 너무 많아서 위임관계가 복잡히 얽혀 있으며 인라인 한다.
함수 추출하기 (Extract Function) # Before def print_owing(invoice): print_banner() outstanding = calculate_outstanding() # 세부 사항 출력 print(f'고객명: {invoice.customer}') print(f'채무액: {outstanding}') # After def print_owing(invoice): def print_detail(outstanding): print(f'고객명': {invoice.customer}) print(f'채무액': {outstanding}) print_banner() outstanding = calculate_outstanding() print_details(outstanding) 배경 코드를 언제 묶어야 하나? 길이 재사용성 목적..

반응형