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 !

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

  • 1.
    Refactor your code:when, why and how?
  • 2.
    2Confidential Nacho Cougil • SeniorSoftware 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 • Whatis 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? • “Legacycode 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 • …donot 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? • Refactoringis 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
  • 7.
  • 8.
  • 9.
    9Confidential • Broken windowstheory (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
  • 10.
  • 11.
    11Confidential • Preparatory • BeforeIneed 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 • Whenweneedtounderstand 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 • Thecode 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 • Weneeda 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 • Theeffort 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 • Includerefactoring 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 istoo 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–Themikadomethod 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 • Todescribe (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 • Builda 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–Withthecode Start testing from the shortest branch Start refactoring fromthe deepest branch
  • 25.
  • 26.
  • 27.
    Confidential 27 • SandroMancuso • 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?
  • 30.

Editor's Notes

  • #5 (It‘s about information and safety)
  • #7 make it easier to understand and cheaper to modify (without changing the observable behavior of the software)
  • #9 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
  • #10 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.
  • #20 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.
  • #27 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”.
  • #28 GOOST >> TDD learn, understand & apply Refactoring to patterns >> shows incremental changes made to transition from a problematic start to the pattern-based end point
  • #30 Nacho