Refactoring and Code Quality

From comments I hear (from both team members and leadership), my sense is that refactoring is not well understood. I’m writing this blog post in hopes of increasing that understanding.

Here are some descriptions that might be useful, for comparison:

User StoriesAdding new functionality
DefectsFixing broken functionality
RefactoringImproving the structure of the code with no change in functionality

Other thoughts on refactoring:

  • Refactoring should be going on constantly. Code naturally experiences entropy: the quality degrades over time as more functionality is added. Refactoring is the way to fight that entropy.
  • Refactoring does not need to be scheduled, like a user story or a defect. Since it is going on constantly every day, it is impractical to try to plan it or account for it. Developers should not need permission to refactor; they own the code quality and they know when it is needed. As an analogy, if you are planning what you might do on a Saturday at home, you might make a “to do” list so you have a plan. But you would probably not put “brush my teeth” on the list – that is just part of the way you live every day. Refactoring is like brushing your teeth. Developers should follow the Boy Scout rule for coding: every day, leave the code a little cleaner than you found it. And you don’t need to account for it in the team’s velocity: if it is going on every day (as it should be), it is already built into their velocity.
  • Without refactoring, velocity will eventually start to decrease. This may seem counterintuitive, since refactoring takes time. But when the quality of the code degrades, it gets harder to work with. It becomes harder to add new functionality when the design has deteriorated. Without constant attention to keep the code clean, pretty soon a story that should be fairly simple and straightforward becomes much more difficult and takes much more time to implement.kitchen-refactoring Think of completing a user story as coming into a kitchen to cook a meal. If the kitchen is a mess, it is going to take you much longer. It will take longer to find that ingredient you need, because it was not put in its proper place. You may need to wash a pan before you can use it, because it was left dirty after the last time it was used. Everything will be slower. But if you come into the kitchen and it is clean and well organized, you’ll be much more productive. Refactoring is the way to keep the code clean.