There’s a lot to be said about how to refactor code. I strongly recommend reading the book Refactoring by Martin Fowler but here are some takeaways primarily from the book:

  • Never add new features, or change functionality when refactoring - first refactor then add.
  • Always start refactoring by first adding a test if they don’t exist, this way you can go from green at start to red while rewriting back to green when you are done.
  • The rule of three: If you find yourself writing similar code in multiple places three times then it’s time to refactor to avoid maintaining three similar versions.
  • Refactoring is part of writing code, it’s part of the job. Don’t reserve time for refactoring “later”.
  • Refactoring shouldn’t be a tedious task. You don’t need to rewrite everything, do it in small pieces and it only takes a few minutes.
  • Don’t expect to simply refactor a large legacy system with no tests - it’s not safe.
  • When we get a bug report, start by writing a test to reproduce the bug. Then fix it.