7. Refactoring 定義
• Refactoring (名詞)
– A change made to the internal structure of
software to make it easier to understand and
cheaper to modify without changing its observable
behavior.
• 除非你想參加 OMG WTF
http://thedailywtf.com/Articles/The-Worse-Than-Failure-Programming-Contest.aspx
“Refactoring: Improving the Design of Existing Code”, Martin Fowler, Kent Beck, et al., 1999 7
8. Any fool can write code
that a computer can understand.
Good programmers write code
that humans can understand.
- Martin Fowler
“Refactoring: Improving the Design of Existing Code”, Martin Fowler, Kent Beck, et al., 1999 8
11. If it stinks,
change it.
—Grandma Beck,
discussing child-rearing philosophy
“Refactoring: Improving the Design of Existing Code”, Martin Fowler, Kent Beck, et al., 1999 11
12. 重構標的 — Code Smells
Within Classes Between Classes
• Comments • Primitive Obsession
• Long Method • Data Clumps
• Long Parameter List • Refused Bequest
• Duplicated Code • Indecent Exposure
• Conditional Complexity • Feature Envy
• Large Class • Lazy Class
• Uncommunicative Name • Divergent Change
• Dead Code • Shotgun Surgery
• … • …
http://www.codinghorror.com/blog/2006/05/code-smells.html, Coding Horror: Code Smells, May 18. 2006 12
13. 怎麼跟老闆講?
• 不用講,做就對了
• 重視品質的老闆
– 他會懂你的
• 嘴巴說重視品質的老闆
– 說了也是白說
– 你真的是在幫他
– The fastest way is to refactor; therefore I refactor.
– Martin Fowler
13
14. 什麼時候該停手
• 程式該砍掉重練時
// When I wrote this, only God and I understood what I was doing
// Now, God only knows
• Deadline 前夕
• 夠好了,對你自己、客戶、還有下個_____
– 明天會更好
– Striving to better, oft we mar what’s well.
– “King Lear” 1.4, William Shakespeare
– Good-Enough Software, “The Pragmatic Programmer”, Andy Hunt, David Thomas
http://stackoverflow.com/questions/184618/what-is-the-best-comment-in-source-code-you-have-ever-encountered 14
17. 移除 Dead Code
• // Don’t do this!
// There was a time, back in the sixties, when
// commenting-out code might have been useful.
• // Nowadays, just delete the code
// We won’t lose it. Promise.
// Revision control system will remember it.
“Clean Code: A Handbook of Agile Software Craftsmanship”, Robert C. Martin, August 2008 17
18. 移除 Dead Code
• Visibility 要盡可能低
– public > protected > package private > private
public void whyNoOneCallsMe() {
// Why am I so useless, how can I not be?
}
private void whyNoOneCallsMe() {
// Why am I so useless, how can I not be?
}
http://sourcemaking.com/implementation-patterns/method-visibility, Method Visibility 18
19. Dead Code 移除小技巧
• 注意 Reduce Visibility 可能的風險
– 介面已經昭告天下時只能 @Deprecated
• Dead Code 不見得都那麼好發現
– 不可能跑到的 if else 或 switch case 區塊
– 請 PMD, FindBugs 幫忙
• 開始用其他重構技巧吧!
– 讓原本的程式更好懂、好修改。
19
45. 參考資料
• “Refactoring: Improving The Design of
Existing code”, Martin Fowler, Kent Beck,
John Brant, William Opdyke, and Don Roberts,
1999
• Code Smells - Jeff Atwood
– http://www.codinghorror.com/blog/2006/05/code-
smells.html
• Web 程式重構 – Jace Ju
– http://www.slideshare.net/jaceju/web-1494836
45