共计 3426 个字符,预计需要花费 9 分钟才能阅读完成。
1. 新手常见问题与痛点分析
刚开始学习编程时,我们常常会写出一些看似能运行但实际上难以维护的代码。以下是一些典型问题:

-
魔法数字 :代码中直接出现的没有解释含义的数字
# Bad if temperature > 30: # 这个 30 是什么?print("太热了") -
超长函数 :一个函数做太多事情,难以理解和修改
// Bad function processOrder(order) { // 验证订单... // 计算价格... // 更新库存... // 发送邮件... // 30 多行代码挤在一起 } -
重复代码 :同样的逻辑在多处出现
# Bad def calculate_area1(radius): return 3.14 * radius * radius def calculate_area2(diameter): return 3.14 * (diameter/2) * (diameter/2)
2. 核心编程原则
2.1 DRY 原则(Don’t Repeat Yourself)
避免重复代码,相同的逻辑应该只在一个地方实现。
2.2 KISS 原则(Keep It Simple, Stupid)
代码应该尽可能简单直接,不要过度设计。
2.3 YAGNI 原则(You Aren’t Gonna Need It)
不要预先实现你认为 ” 将来可能需要 ” 的功能。
2.4 函数单一职责
一个函数应该只做一件事,并且做好这件事。
3. 代码重构实战
3.1 Python 示例
Before(糟糕的代码):
# 1. 魔法数字
# 2. 超长函数
# 3. 重复代码
def process_data(data):
result = []
for item in data:
if item > 50: # 魔法数字 50
temp = item * 0.8 # 处理逻辑 1
else:
temp = item * 0.9 # 处理逻辑 2
if temp > 40: # 又是魔法数字
final = temp + 10
else:
final = temp + 5
result.append(final)
return result
After(优化后的代码):
# 定义常量代替魔法数字
DISCOUNT_THRESHOLD = 50
BASE_DISCOUNT = 0.9
EXTRA_DISCOUNT = 0.8
BONUS_THRESHOLD = 40
SMALL_BONUS = 5
LARGE_BONUS = 10
def apply_discount(price):
"""根据价格应用不同的折扣"""
return price * EXTRA_DISCOUNT if price > DISCOUNT_THRESHOLD else price * BASE_DISCOUNT
def apply_bonus(discounted_price):
"""根据折扣后价格添加奖金"""
return discounted_price + (LARGE_BONUS if discounted_price > BONUS_THRESHOLD else SMALL_BONUS)
def process_data(data):
"""处理数据的主函数"""
return [apply_bonus(apply_discount(item)) for item in data]
3.2 JavaScript 示例
Before(糟糕的代码):
function calculateOrder(order) {
// 计算总价
let total = 0;
for(let item of order.items) {total += item.price * item.quantity;}
// 应用折扣
if(total > 100) {total = total * 0.9;} else if(total > 50) {total = total * 0.95;}
// 计算税费
const tax = total * 0.08;
// 计算运费
let shipping = 5;
if(total > 200) {shipping = 0;} else if(total > 100) {shipping = 3;}
return total + tax + shipping;
}
After(优化后的代码):
// 定义常量
const DISCOUNT_THRESHOLD1 = 50;
const DISCOUNT_THRESHOLD2 = 100;
const DISCOUNT1 = 0.95;
const DISCOUNT2 = 0.9;
const TAX_RATE = 0.08;
const BASE_SHIPPING = 5;
const FREE_SHIPPING_THRESHOLD = 200;
const MID_SHIPPING_THRESHOLD = 100;
const MID_SHIPPING = 3;
function calculateSubtotal(items) {return items.reduce((sum, item) => sum + (item.price * item.quantity), 0);
}
function applyDiscounts(subtotal) {if(subtotal > DISCOUNT_THRESHOLD2) {return subtotal * DISCOUNT2;}
if(subtotal > DISCOUNT_THRESHOLD1) {return subtotal * DISCOUNT1;}
return subtotal;
}
function calculateShipping(subtotal) {if(subtotal > FREE_SHIPPING_THRESHOLD) return 0;
if(subtotal > MID_SHIPPING_THRESHOLD) return MID_SHIPPING;
return BASE_SHIPPING;
}
function calculateOrder(order) {const subtotal = calculateSubtotal(order.items);
const discounted = applyDiscounts(subtotal);
const tax = discounted * TAX_RATE;
const shipping = calculateShipping(discounted);
return discounted + tax + shipping;
}
4. 工具链介绍
4.1 静态代码分析工具
-
Python: flake8
pip install flake8 flake8 your_file.py -
JavaScript: eslint
npm install eslint --save-dev npx eslint your_file.js
4.2 配置 pre-commit 钩子
在项目中添加.pre-commit-config.yaml 文件:
repos:
- repo: https://github.com/pre-commit/pre-commit-hooks
rev: v3.2.0
hooks:
- id: trailing-whitespace
- id: end-of-file-fixer
- id: check-yaml
- repo: https://github.com/PyCQA/flake8
rev: 3.9.2
hooks:
- id: flake8
5. 最容易被忽视的 3 个坏习惯
- 过度注释 :好的代码应该自解释,注释应该解释 ” 为什么 ” 而不是 ” 做什么 ”
- 布尔参数滥用 :布尔参数常常暗示函数做太多事情
# Bad def process(data, is_validate=True, is_log=False): # ... - 过早优化 :在代码可读性和正确性之前追求性能优化
6. 动手挑战
尝试重构以下 Python 代码:
def calculate_grades(students):
result = []
for s in students:
total = 0
count = 0
for subject in s['subjects']:
total += subject['score']
count += 1
avg = total / count
if avg >= 90:
grade = 'A'
elif avg >= 80:
grade = 'B'
elif avg >= 70:
grade = 'C'
elif avg >= 60:
grade = 'D'
else:
grade = 'F'
result.append({'name': s['name'],
'average': avg,
'grade': grade
})
return result
重构提示:
1. 提取计算平均分的逻辑
2. 提取确定成绩等级的逻辑
3. 使用字典代替多层 if-elif
4. 考虑使用列表推导式
希望这篇指南能帮助你写出更干净、更易维护的代码!记住,好的编程习惯需要不断练习和反思。
正文完
