SlideShare a Scribd company logo
1 of 30
Refactor your code: when, why and how?
2Confidential
Nacho Cougil
• Senior Software Engineerat Dynatrace
• TDD &cleancode fan
• Founderof the Barcelona Java Users Group ( BarcelonaJUG ) & co-founderof the
Java andJVMBarcelona Conference
( JBCNConf)
• Father, formermountain marathonrunner 😅
@icougil
WhoamI?
Confidential 3
• What is legacy code and what is refactoring?
• Whyrefactor is {so }important?
• When to refactor code?
• Tips &techniquesfor refactoring
• How to do it?
• Recap
Agenda
Confidential 4
Whatislegacycode?
• “Legacy code is everythingthat is not tested“
MichaelFeathers
• “Today, I stopped refactoring. Todaymyapplication became
legacy”
VictorRentea
• “Valuable code weare afraid to change”
J.B.Rainsberger
Confidential 5
• …do not understand what a particular code does and why?
• ... wehave to workwith themaximum care because we
understand that there can be manyproblems (surgeon
mode)
• ... weare afraid to touch the code
Haveyoufelt thatsensation?
Confidential 6
Whatisrefactoring?
• Refactoring is a disciplined technique for restructuring
an existing body of code, altering its internal structure
without changing its external behaviour
• Refactoring is intended to improve the design,
structure, and/or implementation of
the software (its non-functional attributes), while
preserving its functionality
• So the main goal is… about:
• Improving maintainability
• Better readability
• Reduce complexity
• https://en.wikipedia.org/wiki/Code_refactoring
• “A change made to the internal structure of software to
make it easier to understand and cheaper to modify
without changing its observable behaviour”
Martin Fowler
7Confidential
8Confidential
Whyis refactoring important?
http://martinfowler.com/bliki/DesignStaminaHypothesis.htm
l
http://at4qa.blogspot.com/2010/06/code-refactoring-once-you-meet-it.html
9Confidential
• Broken windows theory (1982)
• “A successful strategy for preventing vandalism, according
to the book's authors, is to address the problems when
they are small”
• Minorcode smells mightlead to completely
degenerated functions, classes, packages software
became complicated &more difficult to maintain
Whyis refactoring important?
https://en.wikipedia.org/wiki/Broken_windows_theory
10Confidential
When?
11Confidential
• Preparatory
• BeforeI need to add a newfeatureor to fix a bug
• As whendoing anexperiment -orcooking- probably
you may needto arrangethescenarioproperly (ex:
preparing theenvironment, collecting theproducts you
need, etc)
• As whentravelling,wemay needto checkthe map and
find thebest routebefore moving
Whento refactor?
12Confidential
• Comprehension
• Whenweneedto understand the codebeforewe
change it
• Do I understand what this code does? Should I refactor it?
• “We are moving our understanding from our head into the
code itself“
WardCunningham
• Whenthe codegetsclearer,wecanfind things on the design
that wecould not seebefore
Whento refactor?
13Confidential
• Litter-pickup
• The code is doing something in a bad way (repeated code, high
complexity, etc)
• BoyScoutrule:“always leave the campground cleaner than you found it”
• Small things ALWAYS matters!
• Renaming avariable tomake it more understandable
• Creating amethod that encapsulates a logic
• Building a new class that holds a particularbehaviour
• Remove unnecessary comments /dead code
Whento refactor?
14Confidential
• Planned
• Weneed a dedicated timeto get theircode base into
a better state for the future
• It maybe a sign that teams areworkingto pay off an
unpaid technical debt
• VSdoing it continuouslyas part of yournaturalflow of
programming(ex: TDD,pair programming)
Whento refactor?
15Confidential
• Long-term
• The effort tomake the change is significantly higher
(weeks vs hours/few days?)
• Theeffort of changingthe status of the code is better than
rewriting it (ex: fix some dependencies inour project,
replace an existing library, etc)
• A dedicated team to workon it VSgradually workon the
problem
Whento refactor?
16Confidential
• Continuously
• Include refactoring as a normalactivity in yourday-to-day
job
• Less effort to do it insmall steps than inbig ones
• More easily adapted when following XP practices (ex:
TDD, codereviews, CI,etc)
• “Just do it”  fast feedback loop will makeyou
programfaster
Whento refactor?
17Confidential
Wait! This is too abstract! Howdoes this land in reality?
Confidential 18
Tips& techniques- Documentyourarchitecturaldecisions
• Example:UKMinistryof Justice- https://github.com/ministryofjustice/form-builder/tree/master/decisions
Confidential 19
Tips& techniques- Analysethedependencies between modules
Confidential 20
Tips& techniques- Withwich moduleto start from?
• Shall we start with the morecomplexmodules or with those that
are changedmostfrequently?
• https://www.stickyminds.com/article/getting-empirical-about-
refactoring
MichaelFeathers
• git log--format=format: --name-only--since=12.month| egrep-v
'^$'|sort |uniq-c|sort -nr|head-50
Churn:the numberof times a file has been modified
Confidential 21
Tips& techniques–The mikadomethod
1. Graba piece of paper
2. Setagoal.Writeitdownon paper.Putitatthetoporatthe center
3. Trytoachievethegoalwithina timebox ( 5 to15min)
• If youfailed❌:
• Revertyour changes.Undowhatyoudidduringthetimebox.
• Thinkaboutwhat’smissing.That’syoursubgoal.
• Writeit downon yourpaperandattach ittothegoalyoutriedtoachieve.
• Startover from3)withyoursubgoal.
• If yousucceeded✅:
• Commit.Stopthetimer.
• Checkthegoalyou achieved onpaper
• Startover from3)withthenext uncheckedsubgoalavailable. Start fromtheleavesofyour
Mikadograph.Iterateuntilyou’vecheckedyourmaingoal.
• https://understandlegacycode.com/blog/a-process-to-do-safe-changes-in-a-complex-
codebase/
• http://mikadomethod.info/
Confidential 22
• To describe (characterize) the actual behaviour of
an existing piece of software
• Its objective is to “protect” existing behaviour of {
legacy}code against unintendedchangesvia
automated testing
• https://en.wikipedia.org/wiki/Characterization_te
st
M.Feathers
Tips& techniques- 1st,characterisation test
Confidential 23
• Build a safety net 🛡 that gives youtheconfidence to make
changes
• Workwith small steps 🛡 &increments
• Keep the code simple (as muchas possible)
• Runyour tests ✅ after each change
• Check 👀 your codecoverage
• Reviewand understand all the refactorings wecanapply
https://www.refactoring.com/catalog/
M.Fowler
Tips& techniques–Withthe code
Confidential 24
Tips& techniques–Withthe code
Start testing from the shortest branch
Start refactoring fromthe deepest branch
Confidential 25
But…. how ???
Confidential 26
Warning –Live coding!
Confidential 27
• Sandro Mancuso
• https://youtu.be/_NnElPO5BU0
• Dave Farley
• https://youtu.be/p-oWHEfXEVs
• Jason Gorman
• https://youtu.be/TSQVb2QoP2A
• Victor Rentea
• https://youtu.be/iOYsxBvMkLk
• NayanHajratwala
• https://youtu.be/1_X9ObRZkk4
Recommendedcontent
Confidential 28
• Importance⚠️ of refactoring
• Thereis no single bullet 🎯
• Different types of refactoring
• {Build &use }a safety net 🛡
• Usethe % coverage to guide 🛡 you
• Understand (& apply) the seam 🛡 technique
• Workwith small increments (useyour DVCS)
• Design yoursoftware with testability inmind
• Rememberthe boyscout rule! 😉
• Practice, practice &practice 🛡 again
Finalrecap
29Confidential
nacho@cougil.com
nacho.cougil@dynatrace.com
https://nacho.cougil.com
@icougil
I’d love 😍 to receive yourfeedback, please:
https://bit.ly/refactoring-feedback-nacho
Questions?
30Confidential
THANKYOU !

More Related Content

What's hot

Test driven development - Zombie proof your code
Test driven development - Zombie proof your codeTest driven development - Zombie proof your code
Test driven development - Zombie proof your codePascal Larocque
 
Tdd is not about testing (C++ version)
Tdd is not about testing (C++ version)Tdd is not about testing (C++ version)
Tdd is not about testing (C++ version)Gianluca Padovani
 
Scrum is not enough - being a successful agile engineer
Scrum is not enough - being a successful agile engineerScrum is not enough - being a successful agile engineer
Scrum is not enough - being a successful agile engineerAnton Keks
 
TDD CrashCourse Part2: TDD
TDD CrashCourse Part2: TDDTDD CrashCourse Part2: TDD
TDD CrashCourse Part2: TDDDavid Rodenas
 
Tdd is not about testing (OOP)
Tdd is not about testing (OOP)Tdd is not about testing (OOP)
Tdd is not about testing (OOP)Gianluca Padovani
 
Adopting Devops , Stories from the trenches
Adopting Devops , Stories from the trenchesAdopting Devops , Stories from the trenches
Adopting Devops , Stories from the trenchesKris Buytaert
 
The View - 30 proven Lotuscript tips
The View - 30 proven Lotuscript tipsThe View - 30 proven Lotuscript tips
The View - 30 proven Lotuscript tipsBill Buchan
 
LCE12: Intro Training: Upstreaming 101
LCE12: Intro Training: Upstreaming 101LCE12: Intro Training: Upstreaming 101
LCE12: Intro Training: Upstreaming 101Linaro
 
Being a professional software tester
Being a professional software testerBeing a professional software tester
Being a professional software testerAnton Keks
 
TDD - Test Driven Development
TDD - Test Driven DevelopmentTDD - Test Driven Development
TDD - Test Driven DevelopmentLim Chanmann
 
Lessons learned with Bdd: a tutorial
Lessons learned with Bdd: a tutorialLessons learned with Bdd: a tutorial
Lessons learned with Bdd: a tutorialAlan Richardson
 
Tdd practices
Tdd practicesTdd practices
Tdd practicesaxykim00
 
Don't get blamed for your choices - Techorama 2019
Don't get blamed for your choices - Techorama 2019Don't get blamed for your choices - Techorama 2019
Don't get blamed for your choices - Techorama 2019Hannes Lowette
 
Engaging Isolation - What I've Learned Delivering 250 Webinar Hours during CO...
Engaging Isolation - What I've Learned Delivering 250 Webinar Hours during CO...Engaging Isolation - What I've Learned Delivering 250 Webinar Hours during CO...
Engaging Isolation - What I've Learned Delivering 250 Webinar Hours during CO...Victor Rentea
 
TDD and Simple Design Workshop - Session 1 - November 2018
TDD and Simple Design Workshop - Session 1 - November 2018TDD and Simple Design Workshop - Session 1 - November 2018
TDD and Simple Design Workshop - Session 1 - November 2018Paulo Clavijo
 

What's hot (20)

Test driven development - Zombie proof your code
Test driven development - Zombie proof your codeTest driven development - Zombie proof your code
Test driven development - Zombie proof your code
 
Tdd is not about testing (C++ version)
Tdd is not about testing (C++ version)Tdd is not about testing (C++ version)
Tdd is not about testing (C++ version)
 
Scrum is not enough - being a successful agile engineer
Scrum is not enough - being a successful agile engineerScrum is not enough - being a successful agile engineer
Scrum is not enough - being a successful agile engineer
 
TDD CrashCourse Part2: TDD
TDD CrashCourse Part2: TDDTDD CrashCourse Part2: TDD
TDD CrashCourse Part2: TDD
 
Tdd is not about testing (OOP)
Tdd is not about testing (OOP)Tdd is not about testing (OOP)
Tdd is not about testing (OOP)
 
Adopting Devops , Stories from the trenches
Adopting Devops , Stories from the trenchesAdopting Devops , Stories from the trenches
Adopting Devops , Stories from the trenches
 
TDD refresher
TDD refresherTDD refresher
TDD refresher
 
The View - 30 proven Lotuscript tips
The View - 30 proven Lotuscript tipsThe View - 30 proven Lotuscript tips
The View - 30 proven Lotuscript tips
 
Test drive on driven development process
Test drive on driven development processTest drive on driven development process
Test drive on driven development process
 
LCE12: Intro Training: Upstreaming 101
LCE12: Intro Training: Upstreaming 101LCE12: Intro Training: Upstreaming 101
LCE12: Intro Training: Upstreaming 101
 
Being a professional software tester
Being a professional software testerBeing a professional software tester
Being a professional software tester
 
TDD - Test Driven Development
TDD - Test Driven DevelopmentTDD - Test Driven Development
TDD - Test Driven Development
 
Lessons learned with Bdd: a tutorial
Lessons learned with Bdd: a tutorialLessons learned with Bdd: a tutorial
Lessons learned with Bdd: a tutorial
 
Tdd practices
Tdd practicesTdd practices
Tdd practices
 
Tdd com Java
Tdd com JavaTdd com Java
Tdd com Java
 
Don't get blamed for your choices - Techorama 2019
Don't get blamed for your choices - Techorama 2019Don't get blamed for your choices - Techorama 2019
Don't get blamed for your choices - Techorama 2019
 
Engaging Isolation - What I've Learned Delivering 250 Webinar Hours during CO...
Engaging Isolation - What I've Learned Delivering 250 Webinar Hours during CO...Engaging Isolation - What I've Learned Delivering 250 Webinar Hours during CO...
Engaging Isolation - What I've Learned Delivering 250 Webinar Hours during CO...
 
TDD and Simple Design Workshop - Session 1 - November 2018
TDD and Simple Design Workshop - Session 1 - November 2018TDD and Simple Design Workshop - Session 1 - November 2018
TDD and Simple Design Workshop - Session 1 - November 2018
 
TDD = bra design?
TDD = bra design?TDD = bra design?
TDD = bra design?
 
Tdd
TddTdd
Tdd
 

Similar to Refactor your code: when, why and how (revisited)

Clean code, Feb 2012
Clean code, Feb 2012Clean code, Feb 2012
Clean code, Feb 2012cobyst
 
How I Learned to Stop Worrying and Love Legacy Code.....
How I Learned to Stop Worrying and Love Legacy Code.....How I Learned to Stop Worrying and Love Legacy Code.....
How I Learned to Stop Worrying and Love Legacy Code.....Mike Harris
 
Cleaning Code - Tools and Techniques for Large Legacy Projects
Cleaning Code - Tools and Techniques for Large Legacy ProjectsCleaning Code - Tools and Techniques for Large Legacy Projects
Cleaning Code - Tools and Techniques for Large Legacy ProjectsMike Long
 
Technical Excellence Doesn't Just Happen--Igniting a Craftsmanship Culture
Technical Excellence Doesn't Just Happen--Igniting a Craftsmanship CultureTechnical Excellence Doesn't Just Happen--Igniting a Craftsmanship Culture
Technical Excellence Doesn't Just Happen--Igniting a Craftsmanship CultureAllison Pollard
 
Devconf 2011 - PHP - How Yii framework is developed
Devconf 2011 - PHP - How Yii framework is developedDevconf 2011 - PHP - How Yii framework is developed
Devconf 2011 - PHP - How Yii framework is developedAlexander Makarov
 
Code refactoring
Code refactoringCode refactoring
Code refactoringLalit Kale
 
TDD - Seriously, try it! (updated '22)
TDD - Seriously, try it! (updated '22)TDD - Seriously, try it! (updated '22)
TDD - Seriously, try it! (updated '22)Nacho Cougil
 
TDD - Seriously, try it! - Trójmiasto Java User Group (17th May '23)
TDD - Seriously, try it! - Trójmiasto Java User Group (17th May '23)TDD - Seriously, try it! - Trójmiasto Java User Group (17th May '23)
TDD - Seriously, try it! - Trójmiasto Java User Group (17th May '23)ssusercaf6c1
 
TDD - Seriously, try it! - Trjjmiasto JUG (17th May '23)
TDD - Seriously, try it! - Trjjmiasto JUG (17th May '23)TDD - Seriously, try it! - Trjjmiasto JUG (17th May '23)
TDD - Seriously, try it! - Trjjmiasto JUG (17th May '23)Nacho Cougil
 
What is the next step for a front end beginner
What is the next step for a front end beginnerWhat is the next step for a front end beginner
What is the next step for a front end beginnerHsuan Fu Lien
 
Get your Project back in Shape!
Get your Project back in Shape!Get your Project back in Shape!
Get your Project back in Shape!Joachim Tuchel
 
DOES16 London - Jonathan Fletcher - Re-imagining Hiscox IT: A DevOps Story
DOES16 London - Jonathan Fletcher - Re-imagining Hiscox IT: A DevOps StoryDOES16 London - Jonathan Fletcher - Re-imagining Hiscox IT: A DevOps Story
DOES16 London - Jonathan Fletcher - Re-imagining Hiscox IT: A DevOps StoryGene Kim
 
Technical Excellence Doesn't Just Happen - AgileIndy 2016
Technical Excellence Doesn't Just Happen - AgileIndy 2016Technical Excellence Doesn't Just Happen - AgileIndy 2016
Technical Excellence Doesn't Just Happen - AgileIndy 2016Allison Pollard
 
TDD - Seriously, try it! - Bucarest Tech Week
TDD - Seriously, try it! - Bucarest Tech WeekTDD - Seriously, try it! - Bucarest Tech Week
TDD - Seriously, try it! - Bucarest Tech WeekNacho Cougil
 
What schools should be teaching IT students
What schools should be teaching IT studentsWhat schools should be teaching IT students
What schools should be teaching IT studentsAndy Lester
 
TDD and Related Techniques for Non Developers (2012)
TDD and Related Techniques for Non Developers (2012)TDD and Related Techniques for Non Developers (2012)
TDD and Related Techniques for Non Developers (2012)Peter Kofler
 
Everyone wants (someone else) to do it: writing documentation for open source...
Everyone wants (someone else) to do it: writing documentation for open source...Everyone wants (someone else) to do it: writing documentation for open source...
Everyone wants (someone else) to do it: writing documentation for open source...Jody Garnett
 

Similar to Refactor your code: when, why and how (revisited) (20)

Clean code, Feb 2012
Clean code, Feb 2012Clean code, Feb 2012
Clean code, Feb 2012
 
How I Learned to Stop Worrying and Love Legacy Code.....
How I Learned to Stop Worrying and Love Legacy Code.....How I Learned to Stop Worrying and Love Legacy Code.....
How I Learned to Stop Worrying and Love Legacy Code.....
 
Cleaning Code - Tools and Techniques for Large Legacy Projects
Cleaning Code - Tools and Techniques for Large Legacy ProjectsCleaning Code - Tools and Techniques for Large Legacy Projects
Cleaning Code - Tools and Techniques for Large Legacy Projects
 
Technical Excellence Doesn't Just Happen--Igniting a Craftsmanship Culture
Technical Excellence Doesn't Just Happen--Igniting a Craftsmanship CultureTechnical Excellence Doesn't Just Happen--Igniting a Craftsmanship Culture
Technical Excellence Doesn't Just Happen--Igniting a Craftsmanship Culture
 
Devconf 2011 - PHP - How Yii framework is developed
Devconf 2011 - PHP - How Yii framework is developedDevconf 2011 - PHP - How Yii framework is developed
Devconf 2011 - PHP - How Yii framework is developed
 
CQRS recepies
CQRS recepiesCQRS recepies
CQRS recepies
 
It's XP, Stupid
It's XP, StupidIt's XP, Stupid
It's XP, Stupid
 
Code refactoring
Code refactoringCode refactoring
Code refactoring
 
TDD - Seriously, try it! (updated '22)
TDD - Seriously, try it! (updated '22)TDD - Seriously, try it! (updated '22)
TDD - Seriously, try it! (updated '22)
 
TDD - Seriously, try it! - Trójmiasto Java User Group (17th May '23)
TDD - Seriously, try it! - Trójmiasto Java User Group (17th May '23)TDD - Seriously, try it! - Trójmiasto Java User Group (17th May '23)
TDD - Seriously, try it! - Trójmiasto Java User Group (17th May '23)
 
TDD - Seriously, try it! - Trjjmiasto JUG (17th May '23)
TDD - Seriously, try it! - Trjjmiasto JUG (17th May '23)TDD - Seriously, try it! - Trjjmiasto JUG (17th May '23)
TDD - Seriously, try it! - Trjjmiasto JUG (17th May '23)
 
What is the next step for a front end beginner
What is the next step for a front end beginnerWhat is the next step for a front end beginner
What is the next step for a front end beginner
 
Code Review
Code ReviewCode Review
Code Review
 
Get your Project back in Shape!
Get your Project back in Shape!Get your Project back in Shape!
Get your Project back in Shape!
 
DOES16 London - Jonathan Fletcher - Re-imagining Hiscox IT: A DevOps Story
DOES16 London - Jonathan Fletcher - Re-imagining Hiscox IT: A DevOps StoryDOES16 London - Jonathan Fletcher - Re-imagining Hiscox IT: A DevOps Story
DOES16 London - Jonathan Fletcher - Re-imagining Hiscox IT: A DevOps Story
 
Technical Excellence Doesn't Just Happen - AgileIndy 2016
Technical Excellence Doesn't Just Happen - AgileIndy 2016Technical Excellence Doesn't Just Happen - AgileIndy 2016
Technical Excellence Doesn't Just Happen - AgileIndy 2016
 
TDD - Seriously, try it! - Bucarest Tech Week
TDD - Seriously, try it! - Bucarest Tech WeekTDD - Seriously, try it! - Bucarest Tech Week
TDD - Seriously, try it! - Bucarest Tech Week
 
What schools should be teaching IT students
What schools should be teaching IT studentsWhat schools should be teaching IT students
What schools should be teaching IT students
 
TDD and Related Techniques for Non Developers (2012)
TDD and Related Techniques for Non Developers (2012)TDD and Related Techniques for Non Developers (2012)
TDD and Related Techniques for Non Developers (2012)
 
Everyone wants (someone else) to do it: writing documentation for open source...
Everyone wants (someone else) to do it: writing documentation for open source...Everyone wants (someone else) to do it: writing documentation for open source...
Everyone wants (someone else) to do it: writing documentation for open source...
 

More from Nacho Cougil

TDD - Seriously, try it! - Opensouthcode
TDD - Seriously, try it! - OpensouthcodeTDD - Seriously, try it! - Opensouthcode
TDD - Seriously, try it! - OpensouthcodeNacho Cougil
 
Introduction to TDD
Introduction to TDDIntroduction to TDD
Introduction to TDDNacho Cougil
 
BarcelonaJUG at GDG summit
BarcelonaJUG at GDG summitBarcelonaJUG at GDG summit
BarcelonaJUG at GDG summitNacho Cougil
 
Be clean, my friend (Clean code review by BarcelonaJUG)
Be clean, my friend (Clean code review by BarcelonaJUG)Be clean, my friend (Clean code review by BarcelonaJUG)
Be clean, my friend (Clean code review by BarcelonaJUG)Nacho Cougil
 
Seghismed - Disseny i desenvolupament d'un esquema criptogràfic per gestionar...
Seghismed - Disseny i desenvolupament d'un esquema criptogràfic per gestionar...Seghismed - Disseny i desenvolupament d'un esquema criptogràfic per gestionar...
Seghismed - Disseny i desenvolupament d'un esquema criptogràfic per gestionar...Nacho Cougil
 

More from Nacho Cougil (6)

TDD - Seriously, try it! - Opensouthcode
TDD - Seriously, try it! - OpensouthcodeTDD - Seriously, try it! - Opensouthcode
TDD - Seriously, try it! - Opensouthcode
 
Introduction to TDD
Introduction to TDDIntroduction to TDD
Introduction to TDD
 
BarcelonaJUG at GDG summit
BarcelonaJUG at GDG summitBarcelonaJUG at GDG summit
BarcelonaJUG at GDG summit
 
Be clean, my friend (Clean code review by BarcelonaJUG)
Be clean, my friend (Clean code review by BarcelonaJUG)Be clean, my friend (Clean code review by BarcelonaJUG)
Be clean, my friend (Clean code review by BarcelonaJUG)
 
Gencat Notifier
Gencat NotifierGencat Notifier
Gencat Notifier
 
Seghismed - Disseny i desenvolupament d'un esquema criptogràfic per gestionar...
Seghismed - Disseny i desenvolupament d'un esquema criptogràfic per gestionar...Seghismed - Disseny i desenvolupament d'un esquema criptogràfic per gestionar...
Seghismed - Disseny i desenvolupament d'un esquema criptogràfic per gestionar...
 

Recently uploaded

Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataAdobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataBradBedford3
 
The Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdfThe Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdfPower Karaoke
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...ICS
 
What is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWhat is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWave PLM
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...MyIntelliSource, Inc.
 
cybersecurity notes for mca students for learning
cybersecurity notes for mca students for learningcybersecurity notes for mca students for learning
cybersecurity notes for mca students for learningVitsRangannavar
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVshikhaohhpro
 
Asset Management Software - Infographic
Asset Management Software - InfographicAsset Management Software - Infographic
Asset Management Software - InfographicHr365.us smith
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...MyIntelliSource, Inc.
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...OnePlan Solutions
 
Engage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The UglyEngage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The UglyFrank van der Linden
 
What is Binary Language? Computer Number Systems
What is Binary Language?  Computer Number SystemsWhat is Binary Language?  Computer Number Systems
What is Binary Language? Computer Number SystemsJheuzeDellosa
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)OPEN KNOWLEDGE GmbH
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfkalichargn70th171
 
chapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptchapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptkotipi9215
 
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfThe Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfkalichargn70th171
 
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...Christina Lin
 
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio, Inc.
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...kellynguyen01
 

Recently uploaded (20)

Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataAdobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
 
The Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdfThe Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdf
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
 
What is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWhat is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need It
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
 
cybersecurity notes for mca students for learning
cybersecurity notes for mca students for learningcybersecurity notes for mca students for learning
cybersecurity notes for mca students for learning
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTV
 
Asset Management Software - Infographic
Asset Management Software - InfographicAsset Management Software - Infographic
Asset Management Software - Infographic
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...
 
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
 
Engage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The UglyEngage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The Ugly
 
What is Binary Language? Computer Number Systems
What is Binary Language?  Computer Number SystemsWhat is Binary Language?  Computer Number Systems
What is Binary Language? Computer Number Systems
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
 
chapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptchapter--4-software-project-planning.ppt
chapter--4-software-project-planning.ppt
 
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfThe Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
 
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
 
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
 

Refactor your code: when, why and how (revisited)

  • 1. Refactor your code: when, why and how?
  • 2. 2Confidential Nacho Cougil • Senior Software Engineerat Dynatrace • TDD &cleancode fan • Founderof the Barcelona Java Users Group ( BarcelonaJUG ) & co-founderof the Java andJVMBarcelona Conference ( JBCNConf) • Father, formermountain marathonrunner 😅 @icougil WhoamI?
  • 3. Confidential 3 • What is legacy code and what is refactoring? • Whyrefactor is {so }important? • When to refactor code? • Tips &techniquesfor refactoring • How to do it? • Recap Agenda
  • 4. Confidential 4 Whatislegacycode? • “Legacy code is everythingthat is not tested“ MichaelFeathers • “Today, I stopped refactoring. Todaymyapplication became legacy” VictorRentea • “Valuable code weare afraid to change” J.B.Rainsberger
  • 5. Confidential 5 • …do not understand what a particular code does and why? • ... wehave to workwith themaximum care because we understand that there can be manyproblems (surgeon mode) • ... weare afraid to touch the code Haveyoufelt thatsensation?
  • 6. Confidential 6 Whatisrefactoring? • Refactoring is a disciplined technique for restructuring an existing body of code, altering its internal structure without changing its external behaviour • Refactoring is intended to improve the design, structure, and/or implementation of the software (its non-functional attributes), while preserving its functionality • So the main goal is… about: • Improving maintainability • Better readability • Reduce complexity • https://en.wikipedia.org/wiki/Code_refactoring • “A change made to the internal structure of software to make it easier to understand and cheaper to modify without changing its observable behaviour” Martin Fowler
  • 9. 9Confidential • Broken windows theory (1982) • “A successful strategy for preventing vandalism, according to the book's authors, is to address the problems when they are small” • Minorcode smells mightlead to completely degenerated functions, classes, packages software became complicated &more difficult to maintain Whyis refactoring important? https://en.wikipedia.org/wiki/Broken_windows_theory
  • 11. 11Confidential • Preparatory • BeforeI need to add a newfeatureor to fix a bug • As whendoing anexperiment -orcooking- probably you may needto arrangethescenarioproperly (ex: preparing theenvironment, collecting theproducts you need, etc) • As whentravelling,wemay needto checkthe map and find thebest routebefore moving Whento refactor?
  • 12. 12Confidential • Comprehension • Whenweneedto understand the codebeforewe change it • Do I understand what this code does? Should I refactor it? • “We are moving our understanding from our head into the code itself“ WardCunningham • Whenthe codegetsclearer,wecanfind things on the design that wecould not seebefore Whento refactor?
  • 13. 13Confidential • Litter-pickup • The code is doing something in a bad way (repeated code, high complexity, etc) • BoyScoutrule:“always leave the campground cleaner than you found it” • Small things ALWAYS matters! • Renaming avariable tomake it more understandable • Creating amethod that encapsulates a logic • Building a new class that holds a particularbehaviour • Remove unnecessary comments /dead code Whento refactor?
  • 14. 14Confidential • Planned • Weneed a dedicated timeto get theircode base into a better state for the future • It maybe a sign that teams areworkingto pay off an unpaid technical debt • VSdoing it continuouslyas part of yournaturalflow of programming(ex: TDD,pair programming) Whento refactor?
  • 15. 15Confidential • Long-term • The effort tomake the change is significantly higher (weeks vs hours/few days?) • Theeffort of changingthe status of the code is better than rewriting it (ex: fix some dependencies inour project, replace an existing library, etc) • A dedicated team to workon it VSgradually workon the problem Whento refactor?
  • 16. 16Confidential • Continuously • Include refactoring as a normalactivity in yourday-to-day job • Less effort to do it insmall steps than inbig ones • More easily adapted when following XP practices (ex: TDD, codereviews, CI,etc) • “Just do it”  fast feedback loop will makeyou programfaster Whento refactor?
  • 17. 17Confidential Wait! This is too abstract! Howdoes this land in reality?
  • 18. Confidential 18 Tips& techniques- Documentyourarchitecturaldecisions • Example:UKMinistryof Justice- https://github.com/ministryofjustice/form-builder/tree/master/decisions
  • 19. Confidential 19 Tips& techniques- Analysethedependencies between modules
  • 20. Confidential 20 Tips& techniques- Withwich moduleto start from? • Shall we start with the morecomplexmodules or with those that are changedmostfrequently? • https://www.stickyminds.com/article/getting-empirical-about- refactoring MichaelFeathers • git log--format=format: --name-only--since=12.month| egrep-v '^$'|sort |uniq-c|sort -nr|head-50 Churn:the numberof times a file has been modified
  • 21. Confidential 21 Tips& techniques–The mikadomethod 1. Graba piece of paper 2. Setagoal.Writeitdownon paper.Putitatthetoporatthe center 3. Trytoachievethegoalwithina timebox ( 5 to15min) • If youfailed❌: • Revertyour changes.Undowhatyoudidduringthetimebox. • Thinkaboutwhat’smissing.That’syoursubgoal. • Writeit downon yourpaperandattach ittothegoalyoutriedtoachieve. • Startover from3)withyoursubgoal. • If yousucceeded✅: • Commit.Stopthetimer. • Checkthegoalyou achieved onpaper • Startover from3)withthenext uncheckedsubgoalavailable. Start fromtheleavesofyour Mikadograph.Iterateuntilyou’vecheckedyourmaingoal. • https://understandlegacycode.com/blog/a-process-to-do-safe-changes-in-a-complex- codebase/ • http://mikadomethod.info/
  • 22. Confidential 22 • To describe (characterize) the actual behaviour of an existing piece of software • Its objective is to “protect” existing behaviour of { legacy}code against unintendedchangesvia automated testing • https://en.wikipedia.org/wiki/Characterization_te st M.Feathers Tips& techniques- 1st,characterisation test
  • 23. Confidential 23 • Build a safety net 🛡 that gives youtheconfidence to make changes • Workwith small steps 🛡 &increments • Keep the code simple (as muchas possible) • Runyour tests ✅ after each change • Check 👀 your codecoverage • Reviewand understand all the refactorings wecanapply https://www.refactoring.com/catalog/ M.Fowler Tips& techniques–Withthe code
  • 24. Confidential 24 Tips& techniques–Withthe code Start testing from the shortest branch Start refactoring fromthe deepest branch
  • 27. Confidential 27 • Sandro Mancuso • https://youtu.be/_NnElPO5BU0 • Dave Farley • https://youtu.be/p-oWHEfXEVs • Jason Gorman • https://youtu.be/TSQVb2QoP2A • Victor Rentea • https://youtu.be/iOYsxBvMkLk • NayanHajratwala • https://youtu.be/1_X9ObRZkk4 Recommendedcontent
  • 28. Confidential 28 • Importance⚠️ of refactoring • Thereis no single bullet 🎯 • Different types of refactoring • {Build &use }a safety net 🛡 • Usethe % coverage to guide 🛡 you • Understand (& apply) the seam 🛡 technique • Workwith small increments (useyour DVCS) • Design yoursoftware with testability inmind • Rememberthe boyscout rule! 😉 • Practice, practice &practice 🛡 again Finalrecap
  • 29. 29Confidential nacho@cougil.com nacho.cougil@dynatrace.com https://nacho.cougil.com @icougil I’d love 😍 to receive yourfeedback, please: https://bit.ly/refactoring-feedback-nacho Questions?

Editor's Notes

  1. (It‘s about information and safety)
  2. make it easier to understand and cheaper to modify (without changing the observable behavior of the software)
  3. Design stamina hypothesis: - at some point new features requires more time to see how to fit into the existing code base - by putting our effort into a good internal design, we increase the stamina of the software effort, allowing us to go faster for longer
  4. Broken windows theory (1982): a criminological theory that states that visible signs of crime, anti-social behavior, and civil disorder create an urban environment that encourages further crime and disorder, including serious crimes.
  5. Dependency Structure Matrix in Intellij / Sonarqube Classes most used in the bottom. All dependencies always flow from GREEN to YELLOW: - when selecting a row, - GREEN annotations show dependent components ( the GREEN depends on X ), - the YELLOW show components on which the selected components depends (the component X depends ON the YELLOW). - Mutual dependencies are shown in RED. shades correspond to the number of dependencies. The more dependencies there are, the darker the corresponding cell is.
  6. https://github.com/sandromancuso/trip-service-kata.git - Seam: “A seam is a place where you can alter behavior in your program without editing in that place.” Excerpt From: Michael C. Feathers. “Working Effectively with Legacy Code”.
  7. GOOST >> TDD learn, understand & apply Refactoring to patterns >> shows incremental changes made to transition from a problematic start to the pattern-based end point
  8. Nacho