SlideShare a Scribd company logo
REFACTORINGXP Injectionhttp://xpinjection.com
Do You Know Your Code?
Developer Golden RuleAny fool can write code that a computer can understand
Good Developer Golden RuleAny fool can write code that a computer can understandGood programmers write code that humans can understand
Why Fix What is Not Broken?
If the Code is Hard to UnderstandHard to maintainHard to improveHard to work with evolutionary designMore expensive
What is Refactoring?A series of small steps, each of which changes the program’s internal structure without changing its external behavior - Martin FowlerVerify no change in external behavior byTestingUsing the right tool (IDE)Formal code analysis by toolCode review or pair programmingBeing very, very careful
Prerequisites for SuccessSafety netEverybody agreed “Collective code ownership”Common understanding of refactoring methodsSupportive environmentPowerful IDE
Refactoring CycleFind smellSelect refactoringApply refactoringRun all tests
3 Ways to Start
Find Something to Improve
Make Static Analysis
Find Smell
How to Find Smell
Smells
Main GoalsOrganizing dataComposing methodsMaking methods calls simplerMoving features between objectsSimplifying conditional expressionDealing with generalizations
Operations Associated with RefactoringReplaceExtractMoveChangeIntroduceRemovePullConsolidatePushInlineAdd
When to Refactor?When add new functionalityRefactor existing code until you understand itRefactor the design to make it simple to addWhen try to find bugsRefactor to understand the codeDuring code reviewsImmediate effect of code reviewAllows for higher level suggestions
Key Elementsof RefactoringSimplifying complex statementsAbstracting common solutions into reusable codeRemoval of duplicate code
Refactoring Techniques
6 Techniques in Action
Extract Methodvoid printOwing() {printBanner();   //print detailsSystem.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);}
Extract Super Class
Decompose Conditionalif (date.before (SUMMER_START) || date.after(SUMMER_END)) {    charge = quantity * winterRate+ serviceCharge;} else {     charge = quantity * summerRate;}if (notSummer(date)) {    charge = winterCharge(quantity);} else {  charge = summerCharge (quantity);}
Replace Error Code with Exceptionboolean withdraw(int amount) {	if (amount > balance)		return false;	else {		balance -= amount;		return true;	}}void withdraw(int amount) throws BalanceException {  if (amount > balance) throw new BalanceException();  balance -= amount;}
Replace Exception with Testdouble getValueForPeriod (int period) {  try {    return values[period];  } catch (ArrayIndexOutOfBoundsException e) {    return 0;  }}double getValueForPeriod (int period) {  return period >= values.length ? 0 : values[period];}
Parameterize Method
Good Design PrinciplesDRYKISSYAGNI
No Silver BulletNeeds lots of practiceRequires disciplineContinuous usageLittle steps
Little steps – huge results
You Need to Pay Technical Debt
Refactoring BenefitsMore readable codeEasier maintenanceCode reuseEasier to add new codeImproved designBetter understandingSpeeding knowledgeEasier to testMinimize duplication 
Live Demo
Questions?

More Related Content

PPT
Working Effectively With Legacy Code
PDF
C++ Unit Test with Google Testing Framework
PDF
Working Effectively with Legacy Code
PDF
Working Effectively with Legacy Code: Lessons in Practice
PDF
An introduction to Google test framework
PDF
Working With Legacy Code
PPT
JMockit
PDF
"Unit Testing for Mobile App" by Fandy Gotama (OLX Indonesia)
Working Effectively With Legacy Code
C++ Unit Test with Google Testing Framework
Working Effectively with Legacy Code
Working Effectively with Legacy Code: Lessons in Practice
An introduction to Google test framework
Working With Legacy Code
JMockit
"Unit Testing for Mobile App" by Fandy Gotama (OLX Indonesia)

What's hot (17)

PDF
Tech In Asia PDC 2017 - Best practice unit testing in mobile apps
PDF
JAVASCRIPT TDD(Test driven Development) & Qunit Tutorial
ODP
Mastering Mock Objects - Advanced Unit Testing for Java
PPTX
Rc2010 tdd
PPT
JMockit Framework Overview
PPT
20111018 boost and gtest
PPT
Testing And Drupal
PDF
Developer Tests - Things to Know (Vilnius JUG)
PPT
Google mock for dummies
PDF
Living With Legacy Code
PPT
Unit Testing in iOS
PPT
Introduzione al TDD
PDF
Unit testing legacy code
PPTX
Unit Testing in Java
PDF
JAVASCRIPT Test Driven Development & Jasmine
ODP
Interaction testing using mock objects
PDF
Cursus phpunit
Tech In Asia PDC 2017 - Best practice unit testing in mobile apps
JAVASCRIPT TDD(Test driven Development) & Qunit Tutorial
Mastering Mock Objects - Advanced Unit Testing for Java
Rc2010 tdd
JMockit Framework Overview
20111018 boost and gtest
Testing And Drupal
Developer Tests - Things to Know (Vilnius JUG)
Google mock for dummies
Living With Legacy Code
Unit Testing in iOS
Introduzione al TDD
Unit testing legacy code
Unit Testing in Java
JAVASCRIPT Test Driven Development & Jasmine
Interaction testing using mock objects
Cursus phpunit
Ad

Viewers also liked (7)

PDF
Eclipse vs. IntelliJ IDEA : Refactorings Showdown
PPTX
Why Do I Hate Hibernate?
PPTX
Club of anonimous developers "Refactoring: Legacy code"
PPT
"В поисках интересной работы" доклад Ольги Шиман
PPTX
Methodologies and technologies used in Ukrainian IT companies
PPTX
kranonitS20 Сергей Бурма. Django - легко, быстро, эффективно
PDF
Spock: A Highly Logical Way To Test
Eclipse vs. IntelliJ IDEA : Refactorings Showdown
Why Do I Hate Hibernate?
Club of anonimous developers "Refactoring: Legacy code"
"В поисках интересной работы" доклад Ольги Шиман
Methodologies and technologies used in Ukrainian IT companies
kranonitS20 Сергей Бурма. Django - легко, быстро, эффективно
Spock: A Highly Logical Way To Test
Ad

Similar to Refactoring (20)

PPTX
Refactoring
PPTX
Clean code
PPT
Code Quality Practice and Tools
PPTX
Tech talks#6: Code Refactoring
PPTX
20.1 Java working with abstraction
PPTX
Combating software entropy 2-roc1-
PPT
TDD And Refactoring
ODP
New Ideas for Old Code - Greach
PDF
Evolving a Clean, Pragmatic Architecture at JBCNConf 2019
PPTX
Introduction to Refactoring
PDF
2018 01-29 - brewbox - refactoring. sempre, senza pietà
PPTX
Working effectively with legacy code
PPT
09 Methods
PPTX
Refactoring and code smells
PPTX
Joomla! Day Chicago 2011 Presentation - Steven Pignataro
PDF
So You Just Inherited a $Legacy Application...
PPTX
Refactoring Workflows & Techniques Presentation by Valentin Stantescu
PDF
Getting Started With Testing
PDF
Introduction Machine Learning by MyLittleAdventure
PDF
So You Just Inherited a $Legacy Application… NomadPHP July 2016
Refactoring
Clean code
Code Quality Practice and Tools
Tech talks#6: Code Refactoring
20.1 Java working with abstraction
Combating software entropy 2-roc1-
TDD And Refactoring
New Ideas for Old Code - Greach
Evolving a Clean, Pragmatic Architecture at JBCNConf 2019
Introduction to Refactoring
2018 01-29 - brewbox - refactoring. sempre, senza pietà
Working effectively with legacy code
09 Methods
Refactoring and code smells
Joomla! Day Chicago 2011 Presentation - Steven Pignataro
So You Just Inherited a $Legacy Application...
Refactoring Workflows & Techniques Presentation by Valentin Stantescu
Getting Started With Testing
Introduction Machine Learning by MyLittleAdventure
So You Just Inherited a $Legacy Application… NomadPHP July 2016

More from Mikalai Alimenkou (20)

PPTX
Rise and fall of Story Points. Capacity based planning from the trenches.
PPTX
Static analysis tools as the best friend of QA
PPTX
Modern CI/CD in the microservices world with Kubernetes
PPTX
Saga about distributed business transactions in microservices world
PPTX
Effectiveness tips from Kubernetes trenches by Captain Obvious
PPTX
Ride the database in JUnit tests with Database Rider
PPTX
Wastful waste or why everything is so slow in development
PPTX
Hexagonal architecture with Spring Boot
PPTX
Wastful waste or why everything is so slow in development
PPTX
DevOps checklist or how to understand where is your team in DevOps landscape ...
PPTX
DevOps checklist or how to understand where is your team in DevOps landscape
PDF
Практические трудности в разработке Медкарты для целой страны
PPTX
Hexagonal architecture with Spring Boot [EPAM Java online conference]
PPTX
Bro, manage test data like a pro! [QA Fest 2018]
PPTX
Agile antipatterns: review after 10 years of practice
PPTX
Hexagonal architecture with Spring Boot
PPTX
Bro, manage test data like a pro!
PPTX
Бытовая классификация тестировщиков с точки зрения разработчика
PPTX
Code Review tool for personal effectiveness and waste analysis
PDF
Funny stories and anti-patterns from DevOps landscape
Rise and fall of Story Points. Capacity based planning from the trenches.
Static analysis tools as the best friend of QA
Modern CI/CD in the microservices world with Kubernetes
Saga about distributed business transactions in microservices world
Effectiveness tips from Kubernetes trenches by Captain Obvious
Ride the database in JUnit tests with Database Rider
Wastful waste or why everything is so slow in development
Hexagonal architecture with Spring Boot
Wastful waste or why everything is so slow in development
DevOps checklist or how to understand where is your team in DevOps landscape ...
DevOps checklist or how to understand where is your team in DevOps landscape
Практические трудности в разработке Медкарты для целой страны
Hexagonal architecture with Spring Boot [EPAM Java online conference]
Bro, manage test data like a pro! [QA Fest 2018]
Agile antipatterns: review after 10 years of practice
Hexagonal architecture with Spring Boot
Bro, manage test data like a pro!
Бытовая классификация тестировщиков с точки зрения разработчика
Code Review tool for personal effectiveness and waste analysis
Funny stories and anti-patterns from DevOps landscape

Recently uploaded (20)

PPTX
Programs and apps: productivity, graphics, security and other tools
PDF
Mobile App Security Testing_ A Comprehensive Guide.pdf
PDF
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
PDF
Per capita expenditure prediction using model stacking based on satellite ima...
PPTX
A Presentation on Artificial Intelligence
PDF
Agricultural_Statistics_at_a_Glance_2022_0.pdf
PPTX
Spectroscopy.pptx food analysis technology
PPTX
Group 1 Presentation -Planning and Decision Making .pptx
PDF
Empathic Computing: Creating Shared Understanding
PDF
Reach Out and Touch Someone: Haptics and Empathic Computing
PDF
MIND Revenue Release Quarter 2 2025 Press Release
PDF
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
PDF
Approach and Philosophy of On baking technology
PDF
Diabetes mellitus diagnosis method based random forest with bat algorithm
PDF
Video forgery: An extensive analysis of inter-and intra-frame manipulation al...
PPTX
TechTalks-8-2019-Service-Management-ITIL-Refresh-ITIL-4-Framework-Supports-Ou...
PDF
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
PDF
Encapsulation_ Review paper, used for researhc scholars
PDF
Network Security Unit 5.pdf for BCA BBA.
PDF
August Patch Tuesday
Programs and apps: productivity, graphics, security and other tools
Mobile App Security Testing_ A Comprehensive Guide.pdf
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
Per capita expenditure prediction using model stacking based on satellite ima...
A Presentation on Artificial Intelligence
Agricultural_Statistics_at_a_Glance_2022_0.pdf
Spectroscopy.pptx food analysis technology
Group 1 Presentation -Planning and Decision Making .pptx
Empathic Computing: Creating Shared Understanding
Reach Out and Touch Someone: Haptics and Empathic Computing
MIND Revenue Release Quarter 2 2025 Press Release
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
Approach and Philosophy of On baking technology
Diabetes mellitus diagnosis method based random forest with bat algorithm
Video forgery: An extensive analysis of inter-and intra-frame manipulation al...
TechTalks-8-2019-Service-Management-ITIL-Refresh-ITIL-4-Framework-Supports-Ou...
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
Encapsulation_ Review paper, used for researhc scholars
Network Security Unit 5.pdf for BCA BBA.
August Patch Tuesday

Refactoring

Editor's Notes

  • #7: We need to realize that software must be soft: it has to be easy to change because it will change despite our misguided efforts otherwise.
  • #10: • Make a small change (a single refactoring)• Run all the tests to ensure everything stillworks• If everything works, move on to the nextrefactoring• If not, fix the problem, or undo the change,so you still have a working system
  • #13: Any time you find that you can improve the design of existing codeYou detect a code that smellsAfter static analysis
  • #14: Any time you find that you can improve the design of existing codeYou detect a code that smellsAfter static analysis