Prevent Code Rot Through
Refactoring – The Code
Agile in a Flash by Jeff Langr and Tim Ottinger (card #47)
> Refactor only while green
> Test constantly
> Work in tiny steps
> Add before removing
> Test extracted functionality
> Do not add functionality
--
Start with all tests passing
(green), because code that does not have tests cannot be safely refactored. If
necessary, add passing characterization tests so that you have a reasonable
green starting point.
By working in tiny steps and
running tests constantly, you will always know whether your last change has
broken anything. Refactoring is much easier if you insist on always having only
one reason to fail.
By adding new code before
removing old code (while testing constantly), you ensure you are not creating
blocks of untested code as you work. For a while, your code will be
half-refactored, with the code of old and new implementations of a behavior
present. Each act of refactoring takes several edit/test cycles to reach a
clean end state. Work deliberately and incrementally.
When extracting classes or
methods, remember that they may need unit tests too, especially if they expose
behaviors that were previously private or hidden. Be watchful of introducing
changes in functionality. When tempted to add some bit of functionality,
complete the current refactoring and move on to the next iteration of the
Red/Green/Refactor cycle.
“Learning to write clean code is
hard work. It requires more than just the knowledge of principles and patterns.
You must sweat over it. You must practice it yourself, and watch yourself fail.
You must watch others practice it and fail. You must see them stumble and
retrace their steps. You must see them agonize over decisions and see the price
they pay for making those decisions the wrong way.” - Martin, Robert C. (2008)
Clean Code: A Handbook of Agile Software Craftmanship. Prentice Hall.
No comments:
Post a Comment