DEV Community

Swarup Kumar Mahapatra
Swarup Kumar Mahapatra

Posted on

When to refactor

We always believe we have put our best efforts while writing code. However following questions come to mind

  • When should one start refactoring, when should one stop refactoring?
  • Doesn’t bias kick in while trying to start refactoring your own code?

Discussion (3)

Collapse
steelwolf180 profile image
Max Ong Zong Bao

1) When you have the time that is dedicated to working on refactoring it. Ideally, you should have test cases to test the piece of code and follows the clean code philosophy that anyone can take it up from there.
2) This is why there's a need for group consensus that you should focus on a style guide and to follow it. Building test cases to test out and reduce the amount of time needed to refactor code.

Collapse
kallmanation profile image
Nathan Kallman

I think there's two times to refactor:

  1. Right after writing code. It's in the phrase red-green-refactor. Said another way that's: figure out what to do, then do it as naively as possible, then figure out how to make it more readable/more modular/more extendable/more reusable/more performant.

  2. Right before writing code. I like to say, "Make it easy; then make the change". Often more junior devs will take a requirement and charge headlong into making it; but it would have been easier and faster if they took a step back and adjusted their helpers/utilities/services/framework to make incorporating the new feature simpler.

One should stop refactoring once the benefits either don't outweigh the costs or become too hypothetical/far in the future.

Collapse
swarupkm profile image
Swarup Kumar Mahapatra Author

Thanks for the response.
The idea of when to stop refactoring was helpful.
I have seen developers of different experience level, refactor differently.

Hence code review feedbacks too vary.

I have seen the "really old developers" have achieved the right balance/zen of refactoring.

The dangerous ones are intermediate ones who over-engineer because they have recently came accross the topics of refactoring and design patterns and overdo it