Description

Most of us know what refactoring is, but are not sure when to refactor the code.

Here is a list of some situations that determine when to refactor.

  • Rule of Three
  • When adding a new feature
  • When fixing a bug
  • During code reviews

Rule of Three

According to this rule, we must consider refactoring when we are doing the same thing for the third time.

  • When we do something for the first time, just do it.
  • When we are doing the same thing for the second time, it's ok to repeat and duplicate.
  • When we are doing the same thing for the third time, it's time to refactor.

When Adding a New Feature

If we need to deal with someone else's messy code to add new functionality, it's always good to refactor the existing code first and then add the new functionality.

  • Refactoring makes the code clean.
  • Making changes to a clean code is easy and bug-free.
  • Improves the existing code along with the new functionality.

When Fixing a Bug

Bugs are always found in the darkest and dirtiest places in the code, and they get easily discovered when we clean the code.

  • Refactoring makes the code clean.
  • Clean code is easy to read and understand, making the bugs discovered easily.

During Code Reviews

Code reviews are very helpful in identifying and cleaning existing messy code when we touch them.

  • Always prefer reviews in a pair with the author, which makes code cleanup quicker.
  • Having multiple reviewers is another way to have multiple eyes on the code.

Overall

We now know when to refactor a piece of code in software development.

Related Links