diff --git a/README.md b/README.md index 289bdcb..f63c386 100644 --- a/README.md +++ b/README.md @@ -1,11 +1,11 @@ # clean-code-python -## Table of Contents - 1. [Introduction](#introduction) - 2. [Variables](#variables) - 3. [Functions](#functions) - 4. [Objects and Data Structures](#objects-and-data-structures) - 5. [Classes](#classes) +## 목차 + 1. [도입](#도입) + 2. [변수](#변수) + 3. [함수](#함수) + 4. [객체와 자료구조](#객체와-자료구조) + 5. [클래스](#클래스) 1. [S: Single Responsibility Principle (SRP)](#single-responsibility-principle-srp) 2. [O: Open/Closed Principle (OCP)](#openclosed-principle-ocp) 3. [L: Liskov Substitution Principle (LSP)](#liskov-substitution-principle-lsp) @@ -13,56 +13,55 @@ 5. [D: Dependency Inversion Principle (DIP)](#dependency-inversion-principle-dip) 6. [Don't repeat yourself (DRY)](#dont-repeat-yourself-dry) -## Introduction +## 도입 -Software engineering principles, from Robert C. Martin's book +소프트웨어 엔지니어링의 원칙으로 불리는 Robert C. Martin의 저서 [*Clean Code*](https://www.amazon.com/Clean-Code-Handbook-Software-Craftsmanship/dp/0132350882), -adapted for Python. This is not a style guide. It's a guide to producing -readable, reusable, and refactorable software in Python. +를 파이썬으로 각색한 버전입니다. 이것은 스타일 가이드가 아닙니다. +파이썬으로 읽기 쉽고, 재사용 가능하며 리팩토링이 가능한 소프트웨워를 제작하는 가이드 입니다. -Not every principle herein has to be strictly followed, and even fewer will be universally -agreed upon. These are guidelines and nothing more, but they are ones codified over many -years of collective experience by the authors of *Clean Code*. +본 문서의 모든 원칙을 엄격하게 준수 할 필요는 없으며, 심지어 더 적은 사람들이 보편적으로 동의할 것입니다. +이것들은 지침일 뿐이지 그 이상은 아니지만, 수년 간 *Clean Code*의 저자들에 의해 축적된 경험들을 통해 체계화된 것들입니다. -Inspired from [clean-code-javascript](https://github.com/ryanmcdermott/clean-code-javascript) +[clean-code-javascript](https://github.com/ryanmcdermott/clean-code-javascript)에서 영감을 얻었습니다. -Targets Python3.7+ +`Python3.7+` 를 대상으로 합니다. -## **Variables** -### Use meaningful and pronounceable variable names +## **변수** +### 의미 있고 발음하기 쉬운 변수 이름을 사용하세요. -**Bad:** +**안 좋은 예:** ```python ymdstr = datetime.date.today().strftime("%y-%m-%d") ``` -**Good**: +**좋은 예:** ```python current_date: str = datetime.date.today().strftime("%y-%m-%d") ``` -**[⬆ back to top](#table-of-contents)** +**[⬆ 맨 위로](#목차)** -### Use the same vocabulary for the same type of variable +### 동일한 유형의 변수에 동일한 어휘를 사용하세요. -**Bad:** -Here we use three different names for the same underlying entity: +**안 좋은 예:** +여기서는 동일한 기본 엔티티(Entity)에 대해 세 가지 다른 이름을 사용합니다.: ```python get_user_info() get_client_data() get_customer_record() ``` -**Good**: -If the entity is the same, you should be consistent in referring to it in your functions: +**좋은 예:** +만약 엔티티(Entity)가 동일하다면 함수에서 엔티티(Entity)를 참조하는 데 일관성이 있어야 합니다.: ```python get_user_info() get_user_data() get_user_record() ``` -**Even better** -Python is (also) an object oriented programming language. If it makes sense, package the functions together with the concrete implementation -of the entity in your code, as instance attributes, property methods, or methods: +**더 나은 예** +파이썬은 (또한) 객체 지향 프로그래밍 언어입니다. 의미가 있다면 코드에서 엔티티(Entity)의 구체적인 구현과 함께 +인스턴스 속성(attributes), 프로퍼티 메소드(property methods) 또는 메소드(methods)로 함수를 패키지화 하십시오: ```python class User: @@ -76,31 +75,35 @@ class User: # ... ``` -**[⬆ back to top](#table-of-contents)** +**[⬆ 맨 위로](#목차)** -### Use searchable names +### 검색 가능한 이름을 사용하세요. We will read more code than we will ever write. It's important that the code we do write is readable and searchable. By *not* naming variables that end up being meaningful for understanding our program, we hurt our readers. Make your names searchable. -**Bad:** +우리는 우리가 작성하는 것보다 더 많은 코드를 읽을 것입니다. 우리가 작성하는 코드를 읽고 검색할 수 있어야 합니다. +프로그램을 이해하기 위해서 의미가 있는 변수이름을 짓지 *않는다*면 코드를 읽는 사람들에게 상처를 줄 수 있습니다. +검색 가능한 이름을 사용하세요. + +**안 좋은 예:** ```python -# What the heck is 86400 for? +# 도대체 86400이 뭐야? time.sleep(86400); ``` -**Good**: +**좋은 예:** ```python -# Declare them in the global namespace for the module. +# 모듈의 전역 네임스페이스에 선언하십시오. SECONDS_IN_A_DAY = 60 * 60 * 24 time.sleep(SECONDS_IN_A_DAY) ``` -**[⬆ back to top](#table-of-contents)** +**[⬆ 맨 위로](#목차)** -### Use explanatory variables -**Bad:** +### 설명적인 변수를 사용하세요. +**안 좋은 예:** ```python address = 'One Infinite Loop, Cupertino 95014' city_zip_code_regex = r'^[^,\\]+[,\\\s]+(.+?)\s*(\d{5})?$' @@ -109,9 +112,9 @@ matches = re.match(city_zip_code_regex, address) save_city_zip_code(matches[1], matches[2]) ``` -**Not bad**: +**나쁘지 않은 예**: -It's better, but we are still heavily dependent on regex. +더 낫지만 여전히 정규표현식에 크게 의존합니다. ```python address = 'One Infinite Loop, Cupertino 95014' @@ -122,9 +125,9 @@ city, zip_code = matches.groups() save_city_zip_code(city, zip_code) ``` -**Good**: +**좋은 예:** -Decrease dependence on regex by naming subpatterns. +하위 패턴의 이름을 지정하여 정규식에 대한 의존성을 줄입니다. ```python address = 'One Infinite Loop, Cupertino 95014' city_zip_code_regex = r'^[^,\\]+[,\\\s]+(?P.+?)\s*(?P\d{5})?$' @@ -132,13 +135,13 @@ matches = re.match(city_zip_code_regex, address) save_city_zip_code(matches['city'], matches['zip_code']) ``` -**[⬆ back to top](#table-of-contents)** +**[⬆ 맨 위로](#목차)** -### Avoid Mental Mapping -Don’t force the reader of your code to translate what the variable means. -Explicit is better than implicit. +### Mental Mapping을 피하세요 +코드를 읽는 사람이 변수의 의미를 번역하도록 강요하지 마세요. +암시적인 것보다 명시적인 것이 좋습니다. -**Bad:** +**안 좋은 예:** ```python seq = ('Austin', 'New York', 'San Francisco') @@ -146,11 +149,11 @@ for item in seq: do_stuff() do_some_other_stuff() # ... - # Wait, what's `item` for again? + # 잠깐만요, `item`이 뭐에요? dispatch(item) ``` -**Good**: +**좋은 예:** ```python locations = ('Austin', 'New York', 'San Francisco') @@ -160,15 +163,14 @@ for location in locations: # ... dispatch(location) ``` -**[⬆ back to top](#table-of-contents)** +**[⬆ 맨 위로](#목차)** -### Don't add unneeded context +### 불필요한 문맥을 추가하지 마세요. -If your class/object name tells you something, don't repeat that in your -variable name. +클래스/객체의 이름이 뭔가를 말한다면 변수 이름에서 반복하지 마세요. -**Bad:** +**안 좋은 예:** ```python class Car: @@ -177,7 +179,7 @@ class Car: car_color: str ``` -**Good**: +**좋은 예:** ```python class Car: @@ -186,9 +188,9 @@ class Car: color: str ``` -**[⬆ back to top](#table-of-contents)** +**[⬆ 맨 위로](#목차)** -### Use default arguments instead of short circuiting or conditionals +### 단락 또는 조건문 대신 기본 인수(arguments)를 사용하세요. **Tricky** @@ -204,7 +206,7 @@ def create_micro_brewery(name): ... when you can specify a default argument instead? This also makes ist clear that you are expecting a string as the argument. -**Good**: +**좋은 예:** ```python def create_micro_brewery(name: str = "Hipster Brew Co."): @@ -212,25 +214,33 @@ def create_micro_brewery(name: str = "Hipster Brew Co."): # etc. ``` -**[⬆ back to top](#table-of-contents)** -## **Functions** -### Function arguments (2 or fewer ideally) +**[⬆ 맨 위로](#목차)** +## **함수** +### 함수 인수(arguments) (2개 이하) Limiting the amount of function parameters is incredibly important because it makes testing your function easier. Having more than three leads to a combinatorial explosion where you have to test tons of different cases with each separate argument. +함수 매개변수(parameter)의 양을 제한하는 것은 함수 테스트를 보다 쉽게 하기 때문에 매우 중요합니다. +세개 이상이면 서로 다른 경우의 수를 각각의 개별 인수(argument)로 다양한 사례를 테스트해야 하기 때문에 조합 폭발로 이어집니다. + Zero arguments is the ideal case. One or two arguments is ok, and three should be avoided. Anything more than that should be consolidated. Usually, if you have more than two arguments then your function is trying to do too much. In cases where it's not, most of the time a higher-level object will suffice as an argument. -**Bad:** +인수(arguments)가 없는 것이 이상적인 경우입니다. 하나 또는 두개의 인수(arguments)는 괜찮으며 세 개는 피해야 합니다. +그 이상은 모두 통합되어야 합니다. 일반적으로 인수(arguments)가 두개 이상이면 함수가 너무 작업을 수행하려고 합니다. +그렇지 않은 경우 대게 상위 객체의 인수로 충분합니다. + + +**안 좋은 예:** ```python def create_menu(title, body, button_text, cancellable): # ... ``` -**Good**: +**좋은 예:** ```python class Menu: def __init__(self, config: dict): @@ -275,7 +285,7 @@ config = MenuConfig config.title = "My delicious menu" config.body = "A description of the various items on the menu" config.button_text = "Order now!" -# The instance attribute overrides the default class attribute. +# 인스턴스 속성(attribute)은 기본 클래스 속성(attribute)보다 우선합니다. config.cancellable = True create_menu(config) @@ -349,16 +359,21 @@ create_menu( ) ``` -**[⬆ back to top](#table-of-contents)** +**[⬆ 맨 위로](#목차)** -### Functions should do one thing +### 함수는 한 가지 일을 해야 합니다. This is by far the most important rule in software engineering. When functions do more than one thing, they are harder to compose, test, and reason about. When you can isolate a function to just one action, they can be refactored easily and your code will read much cleaner. If you take nothing else away from this guide other than this, you'll be ahead of many developers. -**Bad:** +이것은 소프트웨어 엔지니어링에서 단연코 가장 중요한 규칙입니다. +함수가 한 가지 이상의 작업을 수행하면 작성, 테스트 및 추론하기가 더 어렵습니다. +함수를 하나의 동작으로 분리 할 수 있다면 쉽게 리팩토링 할 수 있으며 코드가 훨씬 깔끔해집니다. + + +**안 좋은 예:** ```python def email_clients(clients: List[Client]): @@ -369,7 +384,7 @@ def email_clients(clients: List[Client]): email(client) ``` -**Good**: +**좋은 예:** ```python def get_active_clients(clients: List[Client]) -> List[Client]: """Filter active clients. @@ -402,11 +417,11 @@ def email_client(clients: Iterator[Client]) -> None: ``` -**[⬆ back to top](#table-of-contents)** +**[⬆ 맨 위로](#목차)** ### Function names should say what they do -**Bad:** +**안 좋은 예:** ```python class Email: @@ -430,14 +445,14 @@ message = Email() message.send() ``` -**[⬆ back to top](#table-of-contents)** +**[⬆ 맨 위로](#목차)** ### Functions should only be one level of abstraction When you have more than one level of abstraction, your function is usually doing too much. Splitting up functions leads to reusability and easier testing. -**Bad:** +**안 좋은 예:** ```python def parse_better_js_alternative(code: str) -> None: @@ -494,7 +509,7 @@ def parse(tokens: list) -> list: return syntax_tree ``` -**[⬆ back to top](#table-of-contents)** +**[⬆ 맨 위로](#목차)** ### Don't use flags as function parameters @@ -502,7 +517,7 @@ Flags tell your user that this function does more than one thing. Functions should do one thing. Split your functions if they are following different code paths based on a boolean. -**Bad:** +**안 좋은 예:** ```python from pathlib import Path @@ -526,7 +541,7 @@ def create_temp_file(name: str) -> None: Path('./temp/' + name).touch() ``` -**[⬆ back to top](#table-of-contents)** +**[⬆ 맨 위로](#목차)** ### Avoid side effects @@ -546,7 +561,7 @@ without any structure, using mutable data types that can be written to by anythi or using an instance of a class, and not centralizing where your side effects occur. If you can do this, you will be happier than the vast majority of other programmers. -**Bad:** +**안 좋은 예:** ```python # This is a module-level name. @@ -599,15 +614,15 @@ print(person.name) # 'Ryan McDermott' print(person.name_as_first_and_last) # ['Ryan', 'McDermott'] ``` -**[⬆ back to top](#table-of-contents)** +**[⬆ 맨 위로](#목차)** -## **Objects and Data Structures** +## **객체와 자료구조** *Coming soon* -**[⬆ back to top](#table-of-contents)** +**[⬆ 맨 위로](#목차)** -## **Classes** +## **클래스** ### **Single Responsibility Principle (SRP)** ### **Open/Closed Principle (OCP)** @@ -617,11 +632,11 @@ print(person.name_as_first_and_last) # ['Ryan', 'McDermott'] *Coming soon* -**[⬆ back to top](#table-of-contents)** +**[⬆ 맨 위로](#목차)** ## **Don't repeat yourself (DRY)** *Coming soon* -**[⬆ back to top](#table-of-contents)** +**[⬆ 맨 위로](#목차)**