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?
• What is refactor?
• Why refactor is {so }important?
• When to refactor code?
• Tips for 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
Whyis refactoring important?
http://martinfowler.com/bliki/DesignStaminaHypothesis.htm
l
http://at4qa.blogspot.com/2010/06/code-refactoring-once-you-meet-it.html
8Confidential
• 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
9Confidential
• 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?
10Confidential
• 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?
11Confidential
• 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?
12Confidential
• 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?
13Confidential
• 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?
14Confidential
• 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?
Confidential 15
• 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
• Review 👀 your code coverage
• Usethe tool 🛠 that could work {better }for you.Then,
master it!
Tips
Confidential 16
Tips- How to start?
Start testing from the shortest branch
Start refactoring fromthe deepest branch
Confidential 17
Catalogofrefactorings
• 60refactorings
• https://www.refactoring.com/catalog/
Confidential 18
But….how???
Confidential 19
Warning –Live coding!
Confidential 20
• 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 21
• Importanceof refactoring
• Different typesof 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
22Confidential
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?
23Confidential
THANKYOU !

Refactor your code: when, why and how?

  • 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? • What is refactor? • Why refactor is {so }important? • When to refactor code? • Tips for 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.
    8Confidential • 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
  • 9.
    9Confidential • 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?
  • 10.
    10Confidential • 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?
  • 11.
    11Confidential • 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?
  • 12.
    12Confidential • 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?
  • 13.
    13Confidential • 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?
  • 14.
    14Confidential • 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?
  • 15.
    Confidential 15 • 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 • Review 👀 your code coverage • Usethe tool 🛠 that could work {better }for you.Then, master it! Tips
  • 16.
    Confidential 16 Tips- Howto start? Start testing from the shortest branch Start refactoring fromthe deepest branch
  • 17.
  • 18.
  • 19.
  • 20.
    Confidential 20 • 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
  • 21.
    Confidential 21 • Importanceofrefactoring • Different typesof 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
  • 22.
    22Confidential 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?
  • 23.

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)
  • #8 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
  • #9 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 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”.
  • #21 GOOST >> TDD learn, understand & apply Refactoring to patterns >> shows incremental changes made to transition from a problematic start to the pattern-based end point
  • #23 Nacho