This document discusses principles of refactoring and code smells. It covers reasons for refactoring like improving design and making code more understandable. It provides guidelines on when to refactor, such as after adding features or fixing bugs. Common code smells are also explained like duplicated code, long methods, large classes, and primitive obsession. The document gives refactoring techniques to address each smell, such as extracting methods and classes. It emphasizes that refactoring improves code quality without changing external behavior.
10. 重構與效率 不要浪費無謂的時間 隨時關注效能往往沒有效果 90%的時間花費在10%的程式上 Profiling find hot spot tunning 重構雖然會讓程式變慢,但良好的結構反而讓最佳化容易進行 Write tunable software and then tune it
20. Data clumps 刪定一組中的一個,其他就變得沒有意意 (通常也有 duplication) Extract class Introduce parameter object Preserve whole object 改了後可能產生 feature envy 繼續重構 class A { ... string schema; string host; int port; ... } Class B { ... string schema; string host; int port; ... }
21. Primitive obsession 不愛用小物件,拼命用 primitive Ex: Money, Range, Date, PhoneNumber, ZipCode Replace data with object Replace type code with class Replace type code with subclass Replace type code with state/strategy …
28. Middle man 過度使用 delegation Remove middle man Replace delegation with ingeritance class A { B b; int func1() { return b.func1(); } int func2() { return b.func2(); } int func3() { return b.func3(); } }
29. Inappropriate intimacy 兩個 class 過份親密,互探對方 private Move method Move field Change bidirectional association to unidirectional Extract class Hide delegate class A { friend class B; ... } Class B { friend class A; ... }
30. Alternative classes with different interface Rename method 反覆運用 move method 直到 protocol 一致 或 extract superclass
31. Incomplete library class 3rd-part library 無法更動 Introduce foreign method Introduce local extension
32. Data class 只有 field 跟一堆 getXXX, setXXX Encapsulate field Encapsulate collection Remove setting method Move method 把呼叫行為搬進 data class Hide method 把 public 變成 private