Have you always heard about refactor and it always sounded like a foreign language to you? Have you tried to change code several times but found it impossible to make such changes in several projects? Do you feel overwhelmed when working with legacy code?
Let's see the benefits of refactoring your code and see some tips on how to do it safely!
We will start talking about what is legacy code, what we understand about refactoring and why it is so important nowadays when in most cases we work with software that others have written. Later we will share when we should start thinking on refactoring code and next we will see some recommended techniques to work with legacy code, which will even help us to know where to start and how. And finally, we will see in a live coding session some of the most important and useful refactoring techniques we could apply in our day-to-day job
At the end of this session, I hope you may have learned some tips on how to work with legacy code and how to apply certain techniques to make your day to day more enjoyable ;-)
===
* Presentation shared at Jconf Mexico (October 3rd, 2020) - https://convoca.dev/jconf-mexico-2020/talk/FMDT8Z/ and revisited and updated for sharing at JConf Centro América (December 5th, 2020) https://hopin.to/events/jconf-centroamerica-2020
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?
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
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
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
make it easier to understand and cheaper to modify (without changing the observable behavior of the software)
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
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.
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.
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”.
GOOST >> TDD learn, understand & apply
Refactoring to patterns >> shows incremental changes made to transition from a problematic start to the pattern-based end point