Skip to content

05. Refactor ♻️

The 1, 2, 3 rule for refactoring:

  1. Write something once, thats fine.
  2. Write something twice, thats okay.
  3. Write something three times and it's time to abstract and refactor

The Refactoring Principle, encapsulated in the 1, 2, 3 rule, provides a pragmatic approach to managing code duplication and complexity. This rule helps developers determine when it’s time to refactor code by assessing how often a particular piece of code is written.

  1. Write something once, that's fine. When you write code for the first time, it’s often acceptable to have it in a specific place with minimal abstraction. This initial implementation serves as a starting point and establishes the core functionality.
  2. Write something twice, that's okay. If you encounter the same code pattern or logic a second time, it’s still manageable but indicates a need for caution. At this stage, consider whether the duplication is due to a reusable pattern or if it highlights a potential for future refactoring.
  3. Write something three times and it's time to abstract and refactor. When you find yourself writing the same code three or more times, it’s a clear signal that it’s time to refactor. This repetition indicates that the code can benefit from abstraction and consolidation. Refactoring at this stage helps to eliminate redundancy, improve maintainability, and enhance code readability.

Key aspects of the Refactoring Principle include:

  • Identify Patterns: Look for repeating code patterns or logic that could be abstracted into reusable functions, classes, or modules.
  • Refactor Thoughtfully: When refactoring, aim to improve code structure without altering its functionality. Ensure that the changes enhance clarity, reduce duplication, and simplify maintenance.
  • Test Thoroughly: After refactoring, thoroughly test the code to confirm that the refactoring hasn’t introduced new bugs or issues. Automated tests can be particularly useful for verifying that refactoring maintains existing functionality.
  • Document Changes: Document the rationale behind refactoring decisions and the changes made. This helps to provide context for future developers and ensures that the benefits of refactoring are clear.
  • Iterative Process: Refactoring is an ongoing process. Regularly review and refactor code as needed to keep it clean and maintainable, avoiding the accumulation of technical debt.

By applying the 1, 2, 3 rule, developers can manage code complexity and duplication effectively, leading to a more maintainable and robust codebase.