ask-python-refactor
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
Chinese<critical_constraints>
❌ NO refactoring without tests first
❌ NO single-letter variables (n, x) → use descriptive names
❌ NO functions >20 lines → extract smaller functions
✅ MUST run tests after every change
✅ MUST commit frequently for easy rollback
</critical_constraints>
<naming>
Variables: descriptive nouns (user_count not n)
Functions: verb + object (calculate_total not calc)
Classes: entity nouns (OrderProcessor not OP)
</naming>
<code_smells>
- Duplicated code → extract to shared function
- Long parameter lists → group into dataclass
- Deep nesting → use early returns/guard clauses
- Magic numbers → replace with named constants </code_smells>
<critical_constraints>
❌ 未先编写测试不得进行重构
❌ 禁止使用单字母变量(如n、x)→ 使用具有描述性的名称
❌ 禁止函数长度超过20行 → 拆分出更小的函数
✅ 每次修改后必须运行测试
✅ 必须频繁提交以便于回滚
</critical_constraints>
<naming>
变量:使用描述性名词(如用user_count而非n)
函数:采用“动词+对象”结构(如用calculate_total而非calc)
类:使用实体名词(如用OrderProcessor而非OP)
</naming>
<code_smells>
- 重复代码 → 提取为共享函数
- 过长参数列表 → 分组为dataclass
- 深层嵌套 → 使用提前返回/守卫子句
- 魔法数字 → 替换为具名常量 </code_smells>
Dispatch Tables
调度表
python
undefinedpython
undefinedBefore: long if/elif chains
Before: long if/elif chains
After:
After:
handlers = {'a': process_a, 'b': process_b}
handler = handlers.get(data.type, process_default)
return handler(data)
undefinedhandlers = {'a': process_a, 'b': process_b}
handler = handlers.get(data.type, process_default)
return handler(data)
undefinedType Hints
类型提示
python
def get_user(user_id: int) -> Optional[User]:
return db.find(user_id)python
def get_user(user_id: int) -> Optional[User]:
return db.find(user_id)