From "Refactoring"
🎧 Listen to Summary
Free 10-min PreviewWhen and How to Apply Refactoring
Key Insight
Most refactoring is opportunistic, integrated directly into daily programming tasks rather than scheduled separately. A key guideline for this is the 'Rule of Three': perform a task once, duplicate it and 'wince' the second time, but by the third instance, refactor to eliminate the duplication. This approach means refactoring happens continuously as part of adding features or fixing bugs, rather than being a distinct, time-boxed activity. It ensures that improvements are made precisely when their benefits are most immediate and relevant to the current task.
Preparatory refactoring occurs before adding a new feature or fixing a bug, restructuring existing code to simplify the upcoming task. For example, if a function with conflicting literal values makes adding a feature difficult, one might 'Parameterize Function' instead of copying it, preventing duplication. Comprehension refactoring happens when a developer struggles to understand existing code. Instead of just deciphering it mentally, they refactor it to make its purpose immediately apparent—such as renaming variables or breaking down long functions—effectively moving 'understanding from [the] head into the code itself' for lasting clarity and future benefits.
'Litter-pickup' refactoring is a variation where one understands the code but recognizes it is poorly implemented, such as overly convoluted logic or nearly identical functions that could be parameterized. These quick fixes are done immediately if easy, or noted for later if more extensive. This embodies the 'leave the campsite cleaner than you found it' principle, ensuring continuous, gradual improvement without breaking functionality. While most refactoring is short-term and opportunistic, larger efforts, like replacing a library or component, can be tackled gradually over weeks, using techniques like 'Branch By Abstraction' to introduce new interfaces and migrate calling code incrementally, maintaining a working system throughout.
📚 Continue Your Learning Journey — No Payment Required
Access the complete Refactoring summary with audio narration, key takeaways, and actionable insights from Martin Fowler, Kent Beck.