Why do we refactor?

refactoring

I would like to know the reasons that we do refactoring and justify it. I read a lot of people upset over the idea of refactoring. Refactoring was variously described as:

  1. A result of insufficient upfront
    design.

  2. Undisciplined hacking

  3. A dangerous activity that needlessly risked destabilizing
    working code

  4. A waste of resources.

What are the responsible reasons that lead us to refactor our code?

I also found a similar question here how-often-should-you-refactor, it doesn't provide the reason for refactoring.

Best Solution

Why do we refactor?

Because there's no actual substitute for writing code. No amount of upfront planning or experience can substitute actual code writing. This is what an entire generation (called waterfall) learned the hard way.

Once you start writing the code and be in the middle of it, you reason about the way it works on a lower level you do notice things (performance, usability or correctness things) that escaped the higher design view.

Refactoring is perfecting.

Ask yourself: why do painters do multiple strokes with the brush on the same spot?