vault backup: 2025-08-04 17:10:24

Affected files:
00.00 Inbox/clean code.md
This commit is contained in:
2025-08-04 17:10:25 +08:00
parent f1c989adf7
commit bb558476ce

View File

@@ -17,18 +17,119 @@ description:
- 什麼是Clean Code易讀、易懂、易維護的程式碼
- 技術債務的概念與影響
- 童子軍規則:讓程式碼比接手時更乾淨
Good code:
```python
def calculate_doubled_value_plus_one(input_value):
"""計算輸入值的兩倍加一"""
OFFSET = 1
if input_value <= 0:
raise ValueError("Input value must be positive")
doubled_value = input_value * 2
result = doubled_value + OFFSET
return result
```
Bad code:
```python
def f(x):
if x > 0:
y = x * 2
# TODO: fix this later
z = y + 1 # magic number
return z
else:
return -1
```
- **有意義的命名規範**
- 使用具描述性且明確的變數名稱
- 函式命名:動詞片語表達動作意圖
- 類別命名:名詞表達實體概念
- 避免縮寫和神秘數字
Good code:
```javascript
// 良好的命名
let elapsedTimeInDays;
let activeUsers = [];
let calculateTotalPrice = (price, quantity) => price * quantity;
```
```python
def fetch_user_profile():
return user_profile_data
def validate_user_credentials():
# 驗證使用者憑證
codes.....
```
Bad code:
```javascript
// 糟糕的命名
let d; // 經過的天數
let u = []; // 使用者列表
let calc = (a, b) => a * b;
```
```python
def data():
return user_info
def process():
# 處理某些東西
pass
```
- **函式設計原則**
- 單一職責原則:一個函式只做一件事
- 函式長度控制目標在20行以下
- 參數管理最多3個參數的建議
- 避免副作用與Flag參數
## 一個函式只做一件事
Good code:
```python
# 遵循單一職責的函式
def validate_user_data(user_data):
"""僅負責驗證使用者資料"""
if not user_data.get('email'):
raise ValueError("Email required")
return True
def save_user_to_database(user_data):
"""僅負責儲存資料"""
database.save(user_data)
def send_welcome_notification(email):
"""僅負責發送歡迎郵件"""
email_service.send_welcome_email(email)
def log_user_registration(username):
"""僅負責記錄日誌"""
logger.info(f"User {username} registered successfully")
```
Bad code:
```python
# 違反單一職責的函式
def process_user_data(user_data):
# 驗證資料
if not user_data.get('email'):
raise ValueError("Email required")
# 儲存到資料庫
database.save(user_data)
# 發送通知郵件
email_service.send_welcome_email(user_data['email'])
# 記錄日誌
logger.info(f"User {user_data['name']} processed")
```
- **程式碼組織結構**
- 降層原則:由上到下的閱讀順序