Refactoring Strategies

Guidance rules that states when to refactor:

  • The Rule of Three – Guideline by Don Roberts that states: “The first time you do something, you just do it. The second time you do something similar, you wince at the duplication, but you do the duplicate thing anyway. The third time you do something similar, you refactor.”

  • When a function is being added – There are two possible reasons why the code should be refactored in this case. First is to better understand the code that needs to be changed when the new feature is added. Second reason is when the current code design makes adding the feature much more complicated than it could be with better design.

  • When a bug needs to be fixed – This comes from a reason that when the bug is found, it is a sign that the code was not clear enough for developer to see the bug in the first place.

  • When a code review is being done – Useful in small review groups consisting of author of the code and the reviewer who suggests changes and together they decide if these changes should be applied into the code or not.

  • When a design or code smell is identified – Other time, when the refactoring should also be done whenever a design or code smell is found in the code.

  • Target error-prone modules – one of the effective strategies of refactoring. These are modules that everybody is afraid of which is a good sign that they are more error-prone than others.

  • Target high-complexity modules – These are modules that have the highest complexity ratings. Study done by Henry and Kafura showed that quality of the code improved dramatically when the focus was on these kind of modules.

  • Define an interface between clean code and ugly code, and then move code across the interface – This is very effective strategy for old legacy systems. Every time the developer makes changes to a legacy system, some part of that code should be moved into the clean part of the code. If every developer in the team do this, the quality of the code will be significantly improved.