Back to Coding

When Should You Stop and Rewrite Instead?

When Should You Stop and Rewrite Instead?
AI Tutorials Team 26 June 2026

Debugging assumes the code is worth repairing. Sometimes it is not, and continuing to investigate something that would take an hour to rewrite is a common and expensive habit driven by the effort already spent.

What are the signals?

  • Three failed fixes. Each producing a new problem.
  • Nobody understands it. Including whoever produced it.
  • It is small. Under a couple of hundred lines.
  • The requirements are clear. You know what it should do.
  • It was generated. And never read.

The combination of small and clearly specified is what makes a rewrite cheap, and both are common in exactly the code that resists debugging.

Why is sunk cost the enemy here?

Because the three hours already spent are gone regardless of what you do next. The only question is whether the next hour is better spent debugging or rebuilding, and the previous three should not influence that.

People find this genuinely difficult, which is why the decision is usually made too late.

What is the size threshold?

Roughly what you could rebuild in an afternoon. A function, a module, one screen. Anything larger is not a rewrite decision but a project, and the calculation changes completely.

What must you preserve?

The behaviour, including the parts nobody documented. Code that has been in use encodes decisions about edge cases, and a rewrite that handles only the obvious path is a regression regardless of how much cleaner it is.

Before I replace this: describe everything this code does, including edge cases, unusual inputs it handles, and anything that looks like a deliberate exception. I want a specification, not an explanation.

How do you rewrite safely?

Write the specification, write tests capturing current behaviour where you can, then rebuild against those. That converts a risky replacement into a checkable one.

Keeping the old version until the new one has run for a while is the other sensible precaution.

When is rewriting clearly wrong?

When the code is large, when it has been in production a long time, or when you do not fully know what it does. Old code that survives has usually accumulated fixes for problems you have not encountered, and rebuilding it discards all of them.

What about generated code specifically?

Frequently the right answer for small pieces. A function produced from a description, which nobody read and which is now misbehaving, can be regenerated from a better description in minutes, and that is genuinely cheaper than diagnosing it.

The requirement is a better description, since regenerating from the same one produces the same problem.

What is the honest framing?

This is a cost comparison rather than a defeat. Somebody who rewrites a small module after an hour of failed debugging has made a reasonable judgement; somebody who spends a day on it has made an emotional one.