SlideShare a Scribd company logo
1 of 18
Refactoring – A  way to write a better code Andrew Chaa Part 1
Questions, Slides, and Samples Please feel free to ask questions anytime
Outline Code that smells If it stinks, change it (Kent Beck’s Grandma) Way to improve codes
What can you expect? “Clean code that works”	- Ron Jeffries Higher quality software Methodical approach to software development
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 …
Bad Smells in Code Duplicated Code Long Method Large Class Long Parameter List Divergent Change Switch Statement Temporary Field And many more…
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
void printOwing() { printBanner();     //print details System.out.println ("name:	" + _name); System.out.println ("amount	" + getOutstanding()); } void printOwing() { printBanner(); printDetails(getOutstanding()); } void printDetails (double outstanding) { System.out.println ("name:	" + _name); System.out.println ("amount	" + outstanding); } Extracting Method
Inline Method intgetRating() {     return (moreThanFiveLateDeliveries()) ? 2 : 1; } booleanmoreThanFiveLateDeliveries() {     return _numberOfLateDeliveries > 5; } intgetRating() {     return (_numberOfLateDeliveries > 5) ? 2 : 1; }
Remove Temp double basePrice = anOrder.basePrice(); return (basePrice > 1000) return (anOrder.basePrice() > 1000)
Replace Temp with Query double basePrice = _quantity * _itemPrice; if (basePrice > 1000)     return basePrice * 0.95; else     return basePrice * 0.98; if (basePrice() > 1000)     return basePrice() * 0.95; else     return basePrice() * 0.98; ... double basePrice() { return _quantity * _itemPrice; }
Introduce Explaining Variable if ( (platform.toUpperCase().indexOf("MAC") > -1) &&       (browser.toUpperCase().indexOf("IE") > -1) && wasInitialized() && resize > 0 )  {    // do something  } final booleanisMacOs     = platform.toUpperCase().indexOf("MAC") > -1; final booleanisIEBrowser = browser.toUpperCase().indexOf("IE")  > -1; final booleanwasResized  = resize > 0; if (isMacOs && isIEBrowser && wasInitialized() && wasResized) { 	// do something }
Split Temporary Variable double temp = 2 * (_height + _width); System.out.println (temp); temp = _height * _width; System.out.println (temp); final double perimeter = 2 * (_height + _width); System.out.println (perimeter); final double area = _height * _width; System.out.println (area);
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;
Replace Method with Method Object class Order... 	double price() { 		double primaryBasePrice; 		double secondaryBasePrice; 		double tertiaryBasePrice; 		// long computation; 		... 	}
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();
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 ""; }
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

More Related Content

Featured

2024 State of Marketing Report – by Hubspot
2024 State of Marketing Report – by Hubspot2024 State of Marketing Report – by Hubspot
2024 State of Marketing Report – by HubspotMarius Sescu
 
Everything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPTEverything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPTExpeed Software
 
Product Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage EngineeringsProduct Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage EngineeringsPixeldarts
 
How Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental HealthHow Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental HealthThinkNow
 
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdfAI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdfmarketingartwork
 
PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024Neil Kimberley
 
Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)contently
 
How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024Albert Qian
 
Social Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsSocial Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsKurio // The Social Media Age(ncy)
 
Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Search Engine Journal
 
5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summarySpeakerHub
 
ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd Clark Boyd
 
Getting into the tech field. what next
Getting into the tech field. what next Getting into the tech field. what next
Getting into the tech field. what next Tessa Mero
 
Google's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentGoogle's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentLily Ray
 
Time Management & Productivity - Best Practices
Time Management & Productivity -  Best PracticesTime Management & Productivity -  Best Practices
Time Management & Productivity - Best PracticesVit Horky
 
The six step guide to practical project management
The six step guide to practical project managementThe six step guide to practical project management
The six step guide to practical project managementMindGenius
 
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...RachelPearson36
 

Featured (20)

2024 State of Marketing Report – by Hubspot
2024 State of Marketing Report – by Hubspot2024 State of Marketing Report – by Hubspot
2024 State of Marketing Report – by Hubspot
 
Everything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPTEverything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPT
 
Product Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage EngineeringsProduct Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage Engineerings
 
How Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental HealthHow Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental Health
 
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdfAI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
 
Skeleton Culture Code
Skeleton Culture CodeSkeleton Culture Code
Skeleton Culture Code
 
PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024
 
Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)
 
How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024
 
Social Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsSocial Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie Insights
 
Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024
 
5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary
 
ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd
 
Getting into the tech field. what next
Getting into the tech field. what next Getting into the tech field. what next
Getting into the tech field. what next
 
Google's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentGoogle's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search Intent
 
How to have difficult conversations
How to have difficult conversations How to have difficult conversations
How to have difficult conversations
 
Introduction to Data Science
Introduction to Data ScienceIntroduction to Data Science
Introduction to Data Science
 
Time Management & Productivity - Best Practices
Time Management & Productivity -  Best PracticesTime Management & Productivity -  Best Practices
Time Management & Productivity - Best Practices
 
The six step guide to practical project management
The six step guide to practical project managementThe six step guide to practical project management
The six step guide to practical project management
 
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
 

Refactoring - a discipline to write a better code

  • 1. Refactoring – A way to write a better code Andrew Chaa Part 1
  • 2. Questions, Slides, and Samples Please feel free to ask questions anytime
  • 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
  • 8. void printOwing() { printBanner(); //print details System.out.println ("name: " + _name); System.out.println ("amount " + getOutstanding()); } void printOwing() { printBanner(); printDetails(getOutstanding()); } void printDetails (double outstanding) { System.out.println ("name: " + _name); System.out.println ("amount " + outstanding); } Extracting Method
  • 9. Inline Method intgetRating() { return (moreThanFiveLateDeliveries()) ? 2 : 1; } booleanmoreThanFiveLateDeliveries() { return _numberOfLateDeliveries > 5; } intgetRating() { return (_numberOfLateDeliveries > 5) ? 2 : 1; }
  • 10. Remove Temp double basePrice = anOrder.basePrice(); return (basePrice > 1000) return (anOrder.basePrice() > 1000)
  • 11. Replace Temp with Query double basePrice = _quantity * _itemPrice; if (basePrice > 1000) return basePrice * 0.95; else return basePrice * 0.98; if (basePrice() > 1000) return basePrice() * 0.95; else return basePrice() * 0.98; ... double basePrice() { return _quantity * _itemPrice; }
  • 12. Introduce Explaining Variable if ( (platform.toUpperCase().indexOf("MAC") > -1) && (browser.toUpperCase().indexOf("IE") > -1) && wasInitialized() && resize > 0 ) { // do something } final booleanisMacOs = platform.toUpperCase().indexOf("MAC") > -1; final booleanisIEBrowser = browser.toUpperCase().indexOf("IE") > -1; final booleanwasResized = resize > 0; if (isMacOs && isIEBrowser && wasInitialized() && wasResized) { // do something }
  • 13. Split Temporary Variable double temp = 2 * (_height + _width); System.out.println (temp); temp = _height * _width; System.out.println (temp); final double perimeter = 2 * (_height + _width); System.out.println (perimeter); final double area = _height * _width; System.out.println (area);
  • 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