SlideShare a Scribd company logo
Introduction to Refactoring
About MeVorleakChyEmail (vorleak.chy@gmail.com)Yoolk Inc. (http://www.yoolk.com)Blog (http://vorleakchy.com)Rails Developer.NET Developer
What do we talk about Refactoring?What? Why? When? How?
Get Agile – RefactoringPracticesTools
What is Refactoring?The process of changing a software system in such a way that it does not alter the external behavior of the code, yet improves its internal structure.Fowler, et al., Refactoring, 1999.
BeforeAfterEasier to understandClean codeBetter codeCheaper to modify… MoreUnreadable codeDuplicated codeComplex codeHard to modify… More
Why do we Refactor?The realityExtremely difficult to get the design “right” the first timeHard to fully understand the problem domainHard to understand user requirements, even if the user does!Hard to know how the system will evolve in five yearsOriginal design is often inadequateSystem becomes brittle over time, and more difficult to change
Why do we Refactor? (Cont.)Helps us to deliver more business values fasterImprove code structure and designEasier to maintain and understandEasier to modifyMore flexibilityEasier to add new featuresIncreased re-usability
Why do we Refactor?(Cont.)Keep development at speedTo make the software easier to understandWrite for people, not the compilerUnderstand unfamiliar codeTo help us find bugsRefactor while debugging to clarify the code
ReadabilityWhich code segment is easier to read?Sample 1if (date.before(Summer_Start) || date.after(Summer_End))	charge = quantity * winterRate + winterServiceCharge;else	charge = quantity * summerRate;Sample 2if (isSummer(date))	charge = summerCharge(quantity);else	charge = winterCharge(quantity);
When should werefactor?Add new featuresFix bugsDuring code reviewOnly refactor when refactoring. Do not add features during refactoring
When Not to RefactorSometimes you should throw things out and start againSometimes you are too close to a deadline
Costs of Not RefactoringBad code usually takes more code to do the same thing often because of duplication
How do we Refactor?We looks for Code-SmellsThings that we suspect are not quite right or will cause us severe pain if we do not fix
Common Code SmellsDuplicated codeFeature EnvyCommentsLong MethodLong parameter listSwitch Statements
Duplicated codeThere is obvious duplicationSuch as copy and pasteThere are unobvious duplicationsSuch as parallel inheritance hierarchiesSimilar algorithmsRemedyExtract MethodPull Up Field
Feature EnvyA method that seems more interested in some other classes than the one it is inRemedyMove MethodExtract Method
Extract Methodvoid printOwning(double amount){printBanner();	// print detailsSystem.Console.WriteLine(string.Format(“name: “, name);System.Console.WriteLine(string.Format(“amount: “, amount);}void printOwning(double amount){printBanner();printDetails(amount);}void printDetails(double amount){System.Console.WriteLine(string.Format(“name: “, name);System.Console.WriteLine(string.Format(“amount: “, amount);}
CommentsComments – be suspicious!Comments represent a failure to express an idea in the codeRemedyExtract MethodRename Method
Long MethodGood OO code is easiest to understand and maintain with shorter methods with good namesLong methods tend to be harder to read and understandRemedyExtract MethodReplace Temp with QueryReplace Method with Method ObjectDecompose Conditional
Replace Temp with Querydouble basePrice = _quanity*		_itemPrice;if(basePrice> 1000) {	return basePrice * 0.95;}else {	return basePrice * 0.98;}if(getBasePrice() > 1000) {	return getBasePrice() * 0.95;}else {	return getBasePrice() * 0.98;}double getBasePrice() {	return _quanitiy * _itemPrice;}
Long parameter listFunctions should have as few parameters as possibleRemedyReplace Parameter with MethodPreserve Whole ObjectIntroduce Parameter Object
Introduce Parameter ObjectCustomerCustomeramountInvoicedIn(Date start, Date end)amountRecivedIn(Date start, Date end)amountOverdueIn(Date start, Date end)amountInvoicedIn(DateRangerange)amountRecivedIn(DateRangerange)amountOverdueIn(DateRangerange)
Switch StatementsType cases are evil because they tend to be duplicated many timesRemedyReplace Type Code with SubclassesReplace Type Code with State / StrategyReplace Conditional with PolymorphismReplace Parameter with Explicit MethodsIntroduce Null Object
Replace Parameter with Explicit Methodsvoid setValue(String name, int value){	if(name.Equals(“height”))	{_height = value;return;	}	if(name.Equals(“width”))	{	         _width = value;                 return;         }}void setHeight(intvalue){	_height = value;}void setWidth(intvalue){	_width = value;}
Refactoring CycleChoose on appropriate Refactoring to applyApply RefactoringRun ALL Tests (Get GREEN Bar)Reached Desired Structure?NoYes
Demo
Q & A
Essential Reading
Thank you!

More Related Content

Viewers also liked (8)

PPTX
PhD Dissertation
Patricia Deshane
 
PPT
FSE DS
Patricia Deshane
 
PDF
Method-Level Code Clone Modification using Refactoring Techniques for Clone M...
acijjournal
 
PDF
Patricia Deshane - PhD Dissertation
Patricia Deshane
 
PPTX
ICPC Demo
Patricia Deshane
 
PPT
PhD Proposal
Patricia Deshane
 
PDF
E-LEARNING FOR ALL WITH INTERFACE INCORPORATING KNOWLEDGE ABOUT USER
acijjournal
 
PhD Dissertation
Patricia Deshane
 
Method-Level Code Clone Modification using Refactoring Techniques for Clone M...
acijjournal
 
Patricia Deshane - PhD Dissertation
Patricia Deshane
 
ICPC Demo
Patricia Deshane
 
PhD Proposal
Patricia Deshane
 
E-LEARNING FOR ALL WITH INTERFACE INCORPORATING KNOWLEDGE ABOUT USER
acijjournal
 

Similar to Introduction to Refactoring (20)

PPT
Refactoring Tips by Martin Fowler
Igor Crvenov
 
PPTX
Refactoring
Mikalai Alimenkou
 
PDF
Refactoring: Improve the design of existing code
Valerio Maggio
 
PPT
Code Refactoring
Charlie Berg
 
PDF
Refactoring
Artem Tabalin
 
PPT
Bad Smell in Codes - Part 1
Shaer Hassan
 
PDF
Refactoring PHP
Adam Culp
 
PDF
Refactoring 2TheMax (con ReSharper)
DotNetMarche
 
PDF
Refactoring
Herez Moise Kattan
 
PPTX
Refactoring
ochursina
 
PDF
Bade Smells in Code
Will Shen
 
PPTX
Code smells
Narayann Swaami
 
PPTX
31 days Refactoring
Ahasanul Kalam Akib
 
PDF
Improving your code design using Java
Roan Brasil Monteiro
 
PDF
Learn the Art of Writing Clean Code
Ohad Esperansa
 
PPTX
SAD10 - Refactoring
Michael Heron
 
PDF
July 2012 Ruby Tuesday - Lana Lodge - Refactoring Lighting Talk
ottawaruby
 
PPTX
Code Refactoring
Milan Vukoje
 
PPT
Refactoring - improving the smell of your code
vmandrychenko
 
PPTX
Refactoring Chapter 6,7.pptx
Eskişehir Technical University
 
Refactoring Tips by Martin Fowler
Igor Crvenov
 
Refactoring
Mikalai Alimenkou
 
Refactoring: Improve the design of existing code
Valerio Maggio
 
Code Refactoring
Charlie Berg
 
Refactoring
Artem Tabalin
 
Bad Smell in Codes - Part 1
Shaer Hassan
 
Refactoring PHP
Adam Culp
 
Refactoring 2TheMax (con ReSharper)
DotNetMarche
 
Refactoring
Herez Moise Kattan
 
Refactoring
ochursina
 
Bade Smells in Code
Will Shen
 
Code smells
Narayann Swaami
 
31 days Refactoring
Ahasanul Kalam Akib
 
Improving your code design using Java
Roan Brasil Monteiro
 
Learn the Art of Writing Clean Code
Ohad Esperansa
 
SAD10 - Refactoring
Michael Heron
 
July 2012 Ruby Tuesday - Lana Lodge - Refactoring Lighting Talk
ottawaruby
 
Code Refactoring
Milan Vukoje
 
Refactoring - improving the smell of your code
vmandrychenko
 
Refactoring Chapter 6,7.pptx
Eskişehir Technical University
 
Ad

Recently uploaded (20)

PDF
The Different Types of Non-Experimental Research
Thelma Villaflores
 
PDF
ARAL_Orientation_Day-2-Sessions_ARAL-Readung ARAL-Mathematics ARAL-Sciencev2.pdf
JoelVilloso1
 
PDF
Chapter-V-DED-Entrepreneurship: Institutions Facilitating Entrepreneurship
Dayanand Huded
 
PPTX
MENINGITIS: NURSING MANAGEMENT, BACTERIAL MENINGITIS, VIRAL MENINGITIS.pptx
PRADEEP ABOTHU
 
PPT
Talk on Critical Theory, Part One, Philosophy of Social Sciences
Soraj Hongladarom
 
PPTX
grade 5 lesson matatag ENGLISH 5_Q1_PPT_WEEK4.pptx
SireQuinn
 
PPTX
A PPT on Alfred Lord Tennyson's Ulysses.
Beena E S
 
PDF
The History of Phone Numbers in Stoke Newington by Billy Thomas
History of Stoke Newington
 
PPTX
How to Convert an Opportunity into a Quotation in Odoo 18 CRM
Celine George
 
PPTX
How to Manage Large Scrollbar in Odoo 18 POS
Celine George
 
PDF
BÀI TẬP BỔ TRỢ TIẾNG ANH 8 - GLOBAL SUCCESS - CẢ NĂM - NĂM 2024 (VOCABULARY, ...
Nguyen Thanh Tu Collection
 
PPTX
How to Create a PDF Report in Odoo 18 - Odoo Slides
Celine George
 
PPTX
Cultivation practice of Litchi in Nepal.pptx
UmeshTimilsina1
 
PDF
The-Ever-Evolving-World-of-Science (1).pdf/7TH CLASS CURIOSITY /1ST CHAPTER/B...
Sandeep Swamy
 
PDF
SSHS-2025-PKLP_Quarter-1-Dr.-Kerby-Alvarez.pdf
AishahSangcopan1
 
PDF
Biological Bilingual Glossary Hindi and English Medium
World of Wisdom
 
PDF
Women's Health: Essential Tips for Every Stage.pdf
Iftikhar Ahmed
 
PDF
DIGESTION OF CARBOHYDRATES,PROTEINS,LIPIDS
raviralanaresh2
 
PPTX
I AM MALALA The Girl Who Stood Up for Education and was Shot by the Taliban...
Beena E S
 
PPTX
How to Set Maximum Difference Odoo 18 POS
Celine George
 
The Different Types of Non-Experimental Research
Thelma Villaflores
 
ARAL_Orientation_Day-2-Sessions_ARAL-Readung ARAL-Mathematics ARAL-Sciencev2.pdf
JoelVilloso1
 
Chapter-V-DED-Entrepreneurship: Institutions Facilitating Entrepreneurship
Dayanand Huded
 
MENINGITIS: NURSING MANAGEMENT, BACTERIAL MENINGITIS, VIRAL MENINGITIS.pptx
PRADEEP ABOTHU
 
Talk on Critical Theory, Part One, Philosophy of Social Sciences
Soraj Hongladarom
 
grade 5 lesson matatag ENGLISH 5_Q1_PPT_WEEK4.pptx
SireQuinn
 
A PPT on Alfred Lord Tennyson's Ulysses.
Beena E S
 
The History of Phone Numbers in Stoke Newington by Billy Thomas
History of Stoke Newington
 
How to Convert an Opportunity into a Quotation in Odoo 18 CRM
Celine George
 
How to Manage Large Scrollbar in Odoo 18 POS
Celine George
 
BÀI TẬP BỔ TRỢ TIẾNG ANH 8 - GLOBAL SUCCESS - CẢ NĂM - NĂM 2024 (VOCABULARY, ...
Nguyen Thanh Tu Collection
 
How to Create a PDF Report in Odoo 18 - Odoo Slides
Celine George
 
Cultivation practice of Litchi in Nepal.pptx
UmeshTimilsina1
 
The-Ever-Evolving-World-of-Science (1).pdf/7TH CLASS CURIOSITY /1ST CHAPTER/B...
Sandeep Swamy
 
SSHS-2025-PKLP_Quarter-1-Dr.-Kerby-Alvarez.pdf
AishahSangcopan1
 
Biological Bilingual Glossary Hindi and English Medium
World of Wisdom
 
Women's Health: Essential Tips for Every Stage.pdf
Iftikhar Ahmed
 
DIGESTION OF CARBOHYDRATES,PROTEINS,LIPIDS
raviralanaresh2
 
I AM MALALA The Girl Who Stood Up for Education and was Shot by the Taliban...
Beena E S
 
How to Set Maximum Difference Odoo 18 POS
Celine George
 
Ad

Introduction to Refactoring

  • 2. About MeVorleakChyEmail ([email protected])Yoolk Inc. (http://www.yoolk.com)Blog (http://vorleakchy.com)Rails Developer.NET Developer
  • 3. What do we talk about Refactoring?What? Why? When? How?
  • 4. Get Agile – RefactoringPracticesTools
  • 5. What is Refactoring?The process of changing a software system in such a way that it does not alter the external behavior of the code, yet improves its internal structure.Fowler, et al., Refactoring, 1999.
  • 6. BeforeAfterEasier to understandClean codeBetter codeCheaper to modify… MoreUnreadable codeDuplicated codeComplex codeHard to modify… More
  • 7. Why do we Refactor?The realityExtremely difficult to get the design “right” the first timeHard to fully understand the problem domainHard to understand user requirements, even if the user does!Hard to know how the system will evolve in five yearsOriginal design is often inadequateSystem becomes brittle over time, and more difficult to change
  • 8. Why do we Refactor? (Cont.)Helps us to deliver more business values fasterImprove code structure and designEasier to maintain and understandEasier to modifyMore flexibilityEasier to add new featuresIncreased re-usability
  • 9. Why do we Refactor?(Cont.)Keep development at speedTo make the software easier to understandWrite for people, not the compilerUnderstand unfamiliar codeTo help us find bugsRefactor while debugging to clarify the code
  • 10. ReadabilityWhich code segment is easier to read?Sample 1if (date.before(Summer_Start) || date.after(Summer_End)) charge = quantity * winterRate + winterServiceCharge;else charge = quantity * summerRate;Sample 2if (isSummer(date)) charge = summerCharge(quantity);else charge = winterCharge(quantity);
  • 11. When should werefactor?Add new featuresFix bugsDuring code reviewOnly refactor when refactoring. Do not add features during refactoring
  • 12. When Not to RefactorSometimes you should throw things out and start againSometimes you are too close to a deadline
  • 13. Costs of Not RefactoringBad code usually takes more code to do the same thing often because of duplication
  • 14. How do we Refactor?We looks for Code-SmellsThings that we suspect are not quite right or will cause us severe pain if we do not fix
  • 15. Common Code SmellsDuplicated codeFeature EnvyCommentsLong MethodLong parameter listSwitch Statements
  • 16. Duplicated codeThere is obvious duplicationSuch as copy and pasteThere are unobvious duplicationsSuch as parallel inheritance hierarchiesSimilar algorithmsRemedyExtract MethodPull Up Field
  • 17. Feature EnvyA method that seems more interested in some other classes than the one it is inRemedyMove MethodExtract Method
  • 18. Extract Methodvoid printOwning(double amount){printBanner(); // print detailsSystem.Console.WriteLine(string.Format(“name: “, name);System.Console.WriteLine(string.Format(“amount: “, amount);}void printOwning(double amount){printBanner();printDetails(amount);}void printDetails(double amount){System.Console.WriteLine(string.Format(“name: “, name);System.Console.WriteLine(string.Format(“amount: “, amount);}
  • 19. CommentsComments – be suspicious!Comments represent a failure to express an idea in the codeRemedyExtract MethodRename Method
  • 20. Long MethodGood OO code is easiest to understand and maintain with shorter methods with good namesLong methods tend to be harder to read and understandRemedyExtract MethodReplace Temp with QueryReplace Method with Method ObjectDecompose Conditional
  • 21. Replace Temp with Querydouble basePrice = _quanity* _itemPrice;if(basePrice> 1000) { return basePrice * 0.95;}else { return basePrice * 0.98;}if(getBasePrice() > 1000) { return getBasePrice() * 0.95;}else { return getBasePrice() * 0.98;}double getBasePrice() { return _quanitiy * _itemPrice;}
  • 22. Long parameter listFunctions should have as few parameters as possibleRemedyReplace Parameter with MethodPreserve Whole ObjectIntroduce Parameter Object
  • 23. Introduce Parameter ObjectCustomerCustomeramountInvoicedIn(Date start, Date end)amountRecivedIn(Date start, Date end)amountOverdueIn(Date start, Date end)amountInvoicedIn(DateRangerange)amountRecivedIn(DateRangerange)amountOverdueIn(DateRangerange)
  • 24. Switch StatementsType cases are evil because they tend to be duplicated many timesRemedyReplace Type Code with SubclassesReplace Type Code with State / StrategyReplace Conditional with PolymorphismReplace Parameter with Explicit MethodsIntroduce Null Object
  • 25. Replace Parameter with Explicit Methodsvoid setValue(String name, int value){ if(name.Equals(“height”)) {_height = value;return; } if(name.Equals(“width”)) { _width = value; return; }}void setHeight(intvalue){ _height = value;}void setWidth(intvalue){ _width = value;}
  • 26. Refactoring CycleChoose on appropriate Refactoring to applyApply RefactoringRun ALL Tests (Get GREEN Bar)Reached Desired Structure?NoYes
  • 27. Demo
  • 28. Q & A