refactoring
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseRefactoring
代码重构
A thorough reference covering 89 refactoring techniques and code smells — featuring PHP 8.3+ examples, rationale, step-by-step mechanics, and before/after comparisons.
这份详尽的参考资料涵盖89种重构技术与代码坏味道——附带PHP 8.3+示例、设计思路、分步操作指南,以及重构前后的代码对比。
Refactoring Techniques (67)
重构技术(67种)
Composing Methods
方法组合
- Extract Method — Pull code fragments into named methods → reference
- Inline Method — Substitute a method call with its body → reference
- Extract Variable — Give complex expressions meaningful names through explanatory variables → reference
- Inline Temp — Substitute a temporary variable with its expression → reference
- Replace Temp with Query — Swap temp variables for method calls → reference
- Split Temporary Variable — Assign separate variables for separate purposes → reference
- Remove Assignments to Parameters — Introduce local variables rather than reassigning parameters → reference
- Replace Method with Method Object — Convert a complex method into its own class → reference
- Substitute Algorithm — Swap an algorithm for a clearer alternative → reference
- Extract Method ——将代码片段提取为具名方法 → 参考文档
- Inline Method ——用方法体替代方法调用 → 参考文档
- Extract Variable ——通过解释性变量为复杂表达式赋予有意义的名称 → 参考文档
- Inline Temp ——用表达式替代临时变量 → 参考文档
- Replace Temp with Query ——将临时变量替换为方法调用 → 参考文档
- Split Temporary Variable ——为不同用途分配独立变量 → 参考文档
- Remove Assignments to Parameters ——引入局部变量而非重新赋值参数 → 参考文档
- Replace Method with Method Object ——将复杂方法转换为独立类 → 参考文档
- Substitute Algorithm ——用更清晰的算法替代原有实现 → 参考文档
Moving Features Between Objects
对象间特性迁移
- Move Method — Relocate a method to the class that depends on it most → reference
- Move Field — Relocate a field to the class that depends on it most → reference
- Extract Class — Divide a class that handles too much → reference
- Inline Class — Consolidate a class that does too little → reference
- Hide Delegate — Introduce methods that conceal delegation chains → reference
- Remove Middle Man — Allow clients to call the delegate directly → reference
- Introduce Foreign Method — Attach a missing method to a class you cannot modify → reference
- Introduce Local Extension — Build a wrapper or subclass for a library class → reference
- Move Method ——将方法迁移至最依赖它的类 → 参考文档
- Move Field ——将字段迁移至最依赖它的类 → 参考文档
- Extract Class ——拆分职责过重的类 → 参考文档
- Inline Class ——合并职责过轻的类 → 参考文档
- Hide Delegate ——引入方法以隐藏委托链 → 参考文档
- Remove Middle Man ——允许客户端直接调用委托对象 → 参考文档
- Introduce Foreign Method ——为无法修改的类添加缺失的方法 → 参考文档
- Introduce Local Extension ——为库类构建包装器或子类 → 参考文档
Organizing Data
数据组织
- Self Encapsulate Field — Route field access through getters even within the class → reference
- Replace Data Value with Object — Promote primitive data to a rich object → reference
- Change Value to Reference — Convert value objects into reference objects → reference
- Change Reference to Value — Convert reference objects into value objects → reference
- Replace Array with Object — Swap arrays used as data structures for proper objects → reference
- Duplicate Observed Data — Keep domain data in sync with the UI via Observer → reference
- Change Unidirectional to Bidirectional — Introduce back-references when needed → reference
- Change Bidirectional to Unidirectional — Eliminate unnecessary back-references → reference
- Replace Magic Number with Symbolic Constant — Assign meaningful names to magic numbers → reference
- Encapsulate Field — Restrict field visibility, expose accessors → reference
- Encapsulate Collection — Expose read-only views of collections → reference
- Replace Type Code with Class — Swap type codes for enums or classes → reference
- Replace Type Code with Subclasses — Swap type codes for a class hierarchy → reference
- Replace Type Code with State/Strategy — Swap behavior-affecting type codes for State/Strategy → reference
- Replace Subclass with Fields — Eliminate subclasses that differ only in constants → reference
- Self Encapsulate Field ——即使在类内部也通过 getter 访问字段 → 参考文档
- Replace Data Value with Object ——将原始数据类型升级为富对象 → 参考文档
- Change Value to Reference ——将值对象转换为引用对象 → 参考文档
- Change Reference to Value ——将引用对象转换为值对象 → 参考文档
- Replace Array with Object ——将用作数据结构的数组替换为正规对象 → 参考文档
- Duplicate Observed Data ——通过 Observer 模式保持领域数据与UI同步 → 参考文档
- Change Unidirectional to Bidirectional ——在需要时引入反向引用 → 参考文档
- Change Bidirectional to Unidirectional ——移除不必要的反向引用 → 参考文档
- Replace Magic Number with Symbolic Constant ——为魔术数字赋予有意义的名称 → 参考文档
- Encapsulate Field ——限制字段可见性,暴露访问器 → 参考文档
- Encapsulate Collection ——暴露集合的只读视图 → 参考文档
- Replace Type Code with Class ——将类型码替换为枚举或类 → 参考文档
- Replace Type Code with Subclasses ——将类型码替换为类层次结构 → 参考文档
- Replace Type Code with State/Strategy ——将影响行为的类型码替换为 State/Strategy 模式 → 参考文档
- Replace Subclass with Fields ——移除仅在常量上有差异的子类 → 参考文档
Simplifying Conditional Expressions
条件表达式简化
- Decompose Conditional — Break complex conditionals into named methods → reference
- Consolidate Conditional Expression — Merge conditions that produce the same result → reference
- Consolidate Duplicate Conditional Fragments — Hoist identical code outside of conditionals → reference
- Remove Control Flag — Swap control flags for break/return/continue → reference
- Replace Nested Conditional with Guard Clauses — Flatten nested conditionals using early returns → reference
- Replace Conditional with Polymorphism — Swap conditionals for polymorphic method calls → reference
- Introduce Null Object — Swap null checks for a null object → reference
- Introduce Assertion — Insert assertions to document assumptions → reference
- Decompose Conditional ——将复杂条件拆分为具名方法 → 参考文档
- Consolidate Conditional Expression ——合并产生相同结果的条件 → 参考文档
- Consolidate Duplicate Conditional Fragments ——将条件块外的重复代码提升到外部 → 参考文档
- Remove Control Flag ——用 break/return/continue 替代控制标志 → 参考文档
- Replace Nested Conditional with Guard Clauses ——用提前返回扁平化嵌套条件 → 参考文档
- Replace Conditional with Polymorphism ——用多态方法调用替代条件判断 → 参考文档
- Introduce Null Object ——用 Null 对象替代空值检查 → 参考文档
- Introduce Assertion ——插入断言以记录假设条件 → 参考文档
Simplifying Method Calls
方法调用简化
- Rename Method — Choose method names that reveal their purpose → reference
- Add Parameter — Introduce new parameters to support additional data → reference
- Remove Parameter — Drop unused method parameters → reference
- Separate Query from Modifier — Divide methods that both return values and change state → reference
- Parameterize Method — Unify similar methods by adding a parameter → reference
- Replace Parameter with Explicit Methods — Produce separate methods for each parameter value → reference
- Preserve Whole Object — Pass the entire object rather than individual values → reference
- Replace Parameter with Method Call — Derive values internally instead of passing them in → reference
- Introduce Parameter Object — Bundle related parameters into an object → reference
- Remove Setting Method — Eliminate setters for fields assigned only at creation → reference
- Hide Method — Narrow the visibility of unused public methods → reference
- Replace Constructor with Factory Method — Use factory methods for complex object creation → reference
- Replace Error Code with Exception — Throw exceptions rather than returning error codes → reference
- Replace Exception with Test — Validate conditions upfront instead of catching exceptions → reference
- Rename Method ——选择能体现方法用途的名称 → 参考文档
- Add Parameter ——引入新参数以支持额外数据 → 参考文档
- Remove Parameter ——删除未使用的方法参数 → 参考文档
- Separate Query from Modifier ——拆分既返回值又修改状态的方法 → 参考文档
- Parameterize Method ——通过添加参数统一相似方法 → 参考文档
- Replace Parameter with Explicit Methods ——为每个参数值生成独立方法 → 参考文档
- Preserve Whole Object ——传递整个对象而非单个值 → 参考文档
- Replace Parameter with Method Call ——在内部推导值而非传入参数 → 参考文档
- Introduce Parameter Object ——将相关参数打包为对象 → 参考文档
- Remove Setting Method ——移除仅在创建时赋值的字段的 setter → 参考文档
- Hide Method ——缩小未使用的公共方法的可见性 → 参考文档
- Replace Constructor with Factory Method ——使用工厂方法处理复杂对象创建 → 参考文档
- Replace Error Code with Exception ——抛出异常而非返回错误码 → 参考文档
- Replace Exception with Test ——提前验证条件而非捕获异常 → 参考文档
Dealing with Generalization
泛化处理
- Pull Up Field — Promote identical fields to the superclass → reference
- Pull Up Method — Promote identical methods to the superclass → reference
- Pull Up Constructor Body — Promote shared constructor logic to the superclass → reference
- Push Down Method — Relocate a method to the subclass that uses it → reference
- Push Down Field — Relocate a field to the subclass that uses it → reference
- Extract Subclass — Carve out a subclass for a subset of features → reference
- Extract Superclass — Hoist shared behavior into a parent class → reference
- Extract Interface — Define a shared interface for common operations → reference
- Collapse Hierarchy — Merge superclass and subclass when they are too similar → reference
- Form Template Method — Generalize similar methods into a template → reference
- Replace Inheritance with Delegation — Swap inheritance for composition → reference
- Replace Delegation with Inheritance — Swap excessive delegation for inheritance → reference
- Pull Up Field ——将相同字段提升至父类 → 参考文档
- Pull Up Method ——将相同方法提升至父类 → 参考文档
- Pull Up Constructor Body ——将共享构造逻辑提升至父类 → 参考文档
- Push Down Method ——将方法迁移至使用它的子类 → 参考文档
- Push Down Field ——将字段迁移至使用它的子类 → 参考文档
- Extract Subclass ——为部分特性创建子类 → 参考文档
- Extract Superclass ——将共享行为提取至父类 → 参考文档
- Extract Interface ——为通用操作定义共享接口 → 参考文档
- Collapse Hierarchy ——当父类与子类过于相似时合并它们 → 参考文档
- Form Template Method ——将相似方法泛化为模板方法 → 参考文档
- Replace Inheritance with Delegation ——用组合替代继承 → 参考文档
- Replace Delegation with Inheritance ——用继承替代过度的委托 → 参考文档
Code Smells (22)
代码坏味道(22种)
Bloaters
臃肿类
- Long Method — Methods that have grown excessively long → reference
- Large Class — Classes that try to handle too much → reference
- Primitive Obsession — Excessive use of primitives instead of small objects → reference
- Long Parameter List — Methods accepting too many parameters → reference
- Data Clumps — Groups of data that repeatedly appear together → reference
- Long Method ——过长的方法 → 参考文档
- Large Class ——职责过重的类 → 参考文档
- Primitive Obsession ——过度使用原始类型而非小型对象 → 参考文档
- Long Parameter List ——参数过多的方法 → 参考文档
- Data Clumps ——重复出现的数据组 → 参考文档
Object-Orientation Abusers
面向对象滥用类
- Alternative Classes with Different Interfaces — Similar classes with mismatched method signatures → reference
- Refused Bequest — Subclasses that disregard inherited behavior → reference
- Switch Statements — Complex switch/match constructs that should be polymorphism → reference
- Temporary Field — Fields populated only under certain conditions → reference
- Alternative Classes with Different Interfaces ——相似但方法签名不匹配的类 → 参考文档
- Refused Bequest ——忽略继承行为的子类 → 参考文档
- Switch Statements ——应使用多态替代的复杂 switch/match 结构 → 参考文档
- Temporary Field ——仅在特定条件下被赋值的字段 → 参考文档
Change Preventers
变更阻碍类
- Divergent Change — A single class modified for many unrelated reasons → reference
- Parallel Inheritance Hierarchies — Creating one subclass forces creating another → reference
- Shotgun Surgery — A single change demands edits across many classes → reference
- Divergent Change ——因多种不相关原因被修改的单个类 → 参考文档
- Parallel Inheritance Hierarchies ——创建一个子类时必须同时创建另一个 → 参考文档
- Shotgun Surgery ——单个变更需要修改多个类 → 参考文档
Dispensables
冗余类
- Comments — Excessive comments that mask unclear code → reference
- Duplicate Code — Identical or nearly identical code in multiple locations → reference
- Data Class — Classes consisting of nothing but fields and getters/setters → reference
- Dead Code — Unreachable or unused code → reference
- Lazy Class — Classes that contribute too little to justify their existence → reference
- Speculative Generality — Unused abstractions built "just in case" → reference
- Comments ——掩盖代码不清晰问题的过多注释 → 参考文档
- Duplicate Code ——多处存在的相同或几乎相同的代码 → 参考文档
- Data Class ——仅包含字段和 getter/setter 的类 → 参考文档
- Dead Code ——不可达或未使用的代码 → 参考文档
- Lazy Class ——贡献过少而无存在必要的类 → 参考文档
- Speculative Generality ——为“以防万一”而构建的未使用抽象 → 参考文档
Couplers
耦合类
- Feature Envy — Methods that rely more on another class's data than their own → reference
- Inappropriate Intimacy — Classes that reach into each other's internals → reference
- Incomplete Library Class — Library classes that fall short of providing needed features → reference
- Message Chains — Long chains of method calls (a.b().c().d()) → reference
- Middle Man — Classes that do nothing but delegate to another class → reference
- Feature Envy ——更依赖其他类数据而非自身数据的方法 → 参考文档
- Inappropriate Intimacy ——互相访问内部实现的类 → 参考文档
- Incomplete Library Class ——无法满足需求的库类 → 参考文档
- Message Chains ——过长的方法调用链(如 a.b().c().d()) → 参考文档
- Middle Man ——仅负责委托的类 → 参考文档
Best Practices
最佳实践
- Refactor in small, verified steps — execute tests after every change
- Follow the Boy Scout Rule: leave code in better shape than you found it
- Reach for IDE refactoring tools when available for safe, automated transformations
- Never refactor and alter behavior simultaneously — keep them separate
- Prioritize refactoring that lowers coupling and raises cohesion
- Tackle code smells nearest to your current work first
- 以小而可验证的步骤进行重构——每次变更后执行测试
- 遵循童子军规则:让代码比你接手时更整洁
- 尽可能使用IDE 重构工具以实现安全、自动化的转换
- 切勿同时进行重构和修改行为——将两者分开
- 优先选择能降低耦合度和提高内聚性的重构操作
- 先处理当前工作附近的代码坏味道