3. Outline Code that smells If it stinks, change it (Kent Beck’s Grandma) Way to improve codes
4. What can you expect? “Clean code that works” - Ron Jeffries Higher quality software Methodical approach to software development
5. History of Refactoring Kent Beck and War Cunningham in smalltalk Martin Folwer’s famous book of Refactoring. Supported by various tools now such as VS 2005/8, ReSharper, Eclipse …
6. Bad Smells in Code Duplicated Code Long Method Large Class Long Parameter List Divergent Change Switch Statement Temporary Field And many more…
7. Composing Methods Extract Method Inline Method Inline Temp Replace Temp with Query Introduce Explaining Variable Split Temporary Variable Remove Assignments to Parameters Replace Method with Method Object Substitute Algorithm
14. Remove Assignments to Parameters int discount (intinputVal, int quantity, intyearToDate) { if (inputVal > 50) inputVal -= 2; int discount (intinputVal, int quantity, intyearToDate) { int result = inputVal; if (inputVal > 50) result -= 2;
15. Replace Method with Method Object class Order... double price() { double primaryBasePrice; double secondaryBasePrice; double tertiaryBasePrice; // long computation; ... }
16. Demo Extract method, amountFor(Rental each) Rename variable: thisAmount -> result Moving Method: to Rental, GetCharge Change the reference: each.GetCharge(); Replace Temp with Query: thisAmount Extract Method: frequentRenterPoints Move Method: frequentRenterPoints Remove Temp with Query: GetTotalCharge(); Remove Temp with Query: GetTotalFrequentRenterPoints();
17. Substitute Algorithm String foundPerson(String[] people){ for (inti = 0; i < people.length; i++) { if (people[i].equals ("Don")) { return "Don“;} if (people[i].equals ("John")) { return "John“;} if (people[i].equals ("Kent")) {return "Kent“;} } return ""; } String foundPerson(String[] people){ List candidates = Arrays.asList(new String[] {"Don", "John", "Kent"}); for (inti=0; i<people.length; i++) if (candidates.contains(people[i])) return people[i]; return ""; }
18. Resources Refactoring catalogs: http://www.refactoring.com/catalog/index.html Podcast about Refactoringhttp://www.se-radio.net/index.php?post_id=172668http://www.se-radio.net/index.php?post_id=205444 Refactoring (book)http://www.amazon.co.uk/Refactoring-Improving-Design-Existing-Technology/dp/0201485672/ref=sr_1_1?ie=UTF8&s=books&qid=1246371771&sr=8-1