首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 相關知識

Java 代碼 21 種經典壞味道識別與重構指南

     編輯:Java 相關知識

代碼壞味道清單

  1. Duplicated Code:複製粘貼導致邏輯分散,修改遺漏風險高 → Extract Method / Pull Up Method
  2. Long Method:單方法承擔過多職責,難以理解測試 → Extract Method / Replace Method with Method Object
  3. Large Class:類職責過重,字段方法過多 → Extract Class / Extract Subclass / Extract Interface
  4. Divergent Change:一類因不同原因頻繁變化 → Split Phase / Extract Class 隔離變化維度
  5. Shotgun Surgery:一處修改牽涉多類 → Move Method / Move Field / Inline Class 集中相關邏輯
  6. Feature Envy:方法過度關注他類數據 → Move Method 讓數據擁有者承擔行為
  7. Data Clumps:多處出現相同字段組合 → Extract Class / Introduce Parameter Object 封裝為對象
  8. Primitive Obsession:用基本類型表達領域概念(如 double 表達金額) → Replace Primitive with Object / Replace Type Code with Class
  9. Switch Statements:基於類型碼分支 → Replace Conditional with Polymorphism / Replace Type Code with Subclasses / Strategy
  10. Parallel Inheritance Hierarchies:新增子類必須同步新增另一層次 → Move Method / Move Field 合併層次
  11. Lazy Class:類職責太少,維護成本大於價值 → Inline Class / Collapse Hierarchy
  12. Speculative Generality:為「將來可能」過度設計 → YAGNI 原則,刪除未用代碼
  13. Temporary Field:字段僅特定場景有值 → Extract Class / Introduce Null Object 隔離臨時狀態
  14. Message Chains:a.getB().getC().doSomething() → Hide Delegate / Extract Method 封裝內部結構
  15. Middle Man:類過度委派,無實際邏輯 → Remove Middle Man / Inline Method
  16. Inappropriate Intimacy:兩類過度訪問彼此私有成員 → Move Method / Move Field / Change Bidirectional Association to Unidirectional
  17. Alternative Classes with Different Interfaces:同義操作接口不一致 → Rename Method / Move Method / Extract Superclass 統一協議
  18. Incomplete Library Class:庫類缺失所需功能 → Introduce Foreign Method / Introduce Local Extension
  19. Data Class:純數據容器無行為 → Encapsulate Field / Move Method 賦予行為
  20. Refused Bequest:子類拒絕繼承父類大部分實現 → Replace Inheritance with Delegation
  21. Comments:過度註釋說明代碼本身不清晰 → Rename / Extract Method / Introduce Assertion 讓代碼自述

重構核心原則

  • 小步快跑:每次重構單一壞味道,立即運行測試
  • 測試保護:無測試不重構,先補單元測試
  • 工具輔助:IDE 重構功能(重命名、提取方法、移動方法)可靠高效
  • 持續集成:重構納入日常開發,而非專門階段
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved