1. 何谓重构

重构是对软件内部结构的一种调整,目的是在不改变软件可观察行为的前提下,提高其可理解性,降低其修改成本。

2. 为何重构

  • 改进软件设计
  • 使软件更容易理解
  • 帮助找到bug
  • 提高编程速度

3. 何时重构

  • 添加功能时重构
  • 修补错误时重构
  • 复审代码时重构

4. 坏代码

  1. Duplicated Code(重复代码)
    • Template Method设计模式
  2. Long Method(过长函数)
    • 需要注释说明的内容都需要提炼到独立函数中
    • 提炼循环语句到独立函数
    • 使用Decompose Conditional(238)处理条件表达式
  3. Large Class(过大的类)
    • Extract Class(149)
    • Extract Subclass(330)
  4. Long Parameter List(过长参数列)
    • Replace Parameter with Method(292)
    • Preserve Whole Object(288)
    • Introduce Parameter Object(295)
  5. Divergent Change(发散式变化):一个类受多种变化的影响
    • Extract Class(149)
  6. Shotgun Surgery(***式修改): 一个类变化引发多个类相应修改
    • Move Method(142)
    • Move Field(146)
    • Inline Class(154)
  7. Feature Envy(依恋情结)
  8. Data Clumps(数据泥团)
  9. Primitive Obsession(基本类型偏执)
    • Replace Data Value with Object
  10. Switch Statements
    • 使用多态代替
  11. Parallel Inheritance Hierarchies(平行继承体系)
  12. Lazy Class(冗赘类)
    • Collapse Hierarchy(344)
    • Inline Class(154)
  13. Speculative Generality(夸夸其谈未来性):定义了目前不会用到的类或方法
  14. Temporary Field(令人迷惑的暂时字段)
  15. Message Chains(过度耦合的消息链)
  16. Middle Man(中间人)
  17. Inappropriate Intimacy(狎昵关系)
  18. Alternative Classes with Different Interfaces(异曲同工的类)
  19. Incomplete Library Class(不完美的库类)
    • Introduce Foreign Method(162)
    • Introduce Local Extension(164)
  20. Data Class(纯稚的数据类)
  21. Refused Bequest(被拒绝的遗赠)
    • Replace Inheritance with Delegation(352)
  22. Comments(过多的注释)