code-refactoring-dry
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseCode Refactoring: Don't Repeat Yourself
代码重构:Don't Repeat Yourself
Remove code duplication you just introduced by refactoring duplicated code to follow the DRY principle.
消除你刚刚引入的代码重复,通过重构重复代码来遵循DRY原则。
When to Use This Skill
何时使用此技能
Use this skill when:
- You notice the same logic appearing in multiple places
- Code has been copied and pasted with minor variations
- A change needs to be made in multiple locations
- Following the "NO DUPLICATED CODE!" rule from code review
在以下场景使用此技能:
- 你注意到相同逻辑出现在多个位置
- 代码被复制粘贴且仅有微小差异
- 需要在多个位置进行修改
- 遵循代码审查中的「禁止重复代码!」规则
Instructions
操作步骤
Step 1: Identify the Duplication
步骤1:识别重复代码
Review the files you have been working on in this session to find:
- Duplicated code patterns
- Duplicated logic or structures
- Copied and pasted blocks with minor variations
回顾你在本次会话中处理的文件,找出:
- 重复的代码模式
- 重复的逻辑或结构
- 复制粘贴后仅有微小差异的代码块
Step 2: Clarify Scope (If Needed)
步骤2:明确范围(如有需要)
If the duplication is not obvious, ask the user to clarify which specific
duplication they want addressed before proceeding.
如果重复代码不明显,请在继续之前请求用户明确指出他们想要处理的具体重复内容。
Step 3: Refactor
步骤3:重构
Once the duplication is identified:
- Extract shared logic into reusable functions, classes, or modules
- Replace duplicated code with calls to the shared implementation
- Ensure the refactoring maintains the same functionality
- Update all call sites to use the new shared implementation
一旦识别出重复代码:
- 将共享逻辑提取到可复用的函数、类或模块中
- 用对共享实现的调用替换重复代码
- 确保重构后功能保持不变
- 更新所有调用位置以使用新的共享实现
Step 4: Verify
步骤4:验证
After refactoring:
- Run tests if available
- Verify the code still works as expected
- Check that the solution is cleaner and more maintainable
重构完成后:
- 如果有测试用例,请运行测试
- 验证代码仍能按预期工作
- 检查解决方案是否更简洁、更易于维护
Goal
目标
Eliminate unnecessary duplication while maintaining code clarity and
functionality. The refactored code should be easier to maintain and modify
in the future.
在保持代码清晰性和功能性的同时消除不必要的重复。重构后的代码应在未来更易于维护和修改。
Benefits of DRY
DRY原则的优势
- Single source of truth: Changes only need to be made in one place
- Easier maintenance: Bug fixes propagate automatically
- Reduced risk: Consistency is enforced
- Better testing: Test shared logic once
- 单一事实来源:仅需在一处进行修改
- 更易维护:漏洞修复会自动生效
- 降低风险:确保一致性
- 更优测试:只需测试一次共享逻辑