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?

Image of Datadog

The Essential Toolkit for Front-end Developers

Take a user-centric approach to front-end monitoring that evolves alongside increasingly complex frameworks and single-page applications.

Get The Kit

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay