clean code 작성

2022. 7. 25. 15:31프로그래밍 언어/규칙

clean code 작성하기

 

 

출처 : https://dev.to/alexomeyer/10-must-know-patterns-for-writing-clean-code-with-python-56bf

 

1. clean code 작성

01 설명이 포함된 긴 이름 사용 (읽기 쉬운 형태) // 애매모호하게 줄인 변수명금지

total_active_users

# 1. 설명이 포함된 긴 변수명 사용
# Not recommended
# The au variable is the number of active users
au = 105

# Recommended 
total_active_users = 105


# 애매모호하게 줄인 변수명 사용금지
# Not recommended
fn = 'John'
Ln = ‘Doe’
cre_tmstp = 1621535852

# Recommended
first_name = ‘JOhn’
Las_name = ‘Doe’
creation_timestamp = 1621535852

 

 

02 의도파악이 가능한 변수이름 사용

for city in cities

# Not recommended
c = [“UK”, “USA”, “UAE”]

for x in c:
print(x)

# Recommended
cities = [“UK”, “USA”, “UAE”]
    for city in cities:
        print(city)


03 일관성을 유지하기

# 1. 변수명 명명시 일관성유지
# Not recommended
client_first_name = ‘John’
customer_last_name = ‘Doe;

# Recommended
client_first_name = ‘John’
client_last_name = ‘Doe’

# 2. 함수명 명명시 일관성유지
# Not recommended
def get_users(): 
    # do something
    Pass

def fetch_user(id): 
    # do something
    Pass
    
# Recommended
def fetch_users(): 
    # do something
    Pass

def fetch_user(id): 
    # do something
    Pass

 

04 의미 알 수 없는 숫자사용금지

import random

# Not recommended
def roll_dice():
    return random.randint(0, 4)  # what is 4 supposed to represent?

# Recommended
DICE_SIDES = 4

def roll_dice():
    return random.randint(0, DICE_SIDES)

 

05 함수는 한가지 역할만 잘하면 됨 

# 여러 기능을 한 함수에 모음
# Not recommended
def fetch_and_display_users():
	users = [] # result from some api call
    for user in users:
        print(user)

# 각 함수는 한가지역할만 수행
# Recommended
def fetch_usersl():
    users = [] # result from some api call
    return users

def display_users(users):
	for user in users:
        print(user)
        
        
        
# Boolean flags 사용치 말고 분리
text = "Python is a simple and elegant programming language."

# Not recommended
def transform_text(text, uppercase):
    if uppercase:
        return text.upper()
    else:
        return text.lower()

uppercase_text = transform_text(text, True)
lowercase_text = transform_text(text, False)


# Recommended
def transform_to_uppercase(text):
    return text.upper()

def transform_to_lowercase(text):
    return text.lower()

uppercase_text = transform_to_uppercase(text)
lowercase_text = transform_to_lowercase(text)

 

06 클래스선언시 불필요한(중복되는) 단어는 추가금지

# Not recommended
class Person:
    def __init__(self, person_username, person_email, person_phone, person_address):
        self.person_username = person_username
        self.person_email = person_email
        self.person_phone = person_phone
        self.person_address = person_address

# Recommended
class Person:
    def __init__(self, username, email, phone, address):

        self.username = username
        self.email = email
        self.phone = phone
        self.address = address