DEV Community

Łukasz Reszke
Łukasz Reszke

Posted on

When to refactor?

When should I refactor?


Always. 

Not kidding.

Have you ever experienced a situation when there was a small piece of functionality that had to be added to existing code?

Did you then think that if you would change the existing structure, just a little bit, it would be piece of cake to add the new feature here?

That was the right thinking. It’s a way better direction to take instead of copy-pasting function and changing only the piece of code that you need.

This way the code would end up with duplicated logic, which needs to be changed in multiple places, whenever business logic changes (and you have to find that code in multiple places).

Seriously always?


Well. There’s a but.
You should have tests.

Either way, how can you verify that one of the key aspects of refactoring is fulfilled?

The one that is saying there’s no change in observable behavior.

If you don’t have tests, write them before you start.


There are three major benefits of that:

  1. The test will let you know whenever you broke functionality, so you’ll have to do more confidence doing small changes
  2. You’ll get to understand code better
  3. Tests often lead to simple & elegant solutions 


Do you do continuous refactoring?

Top comments (0)