Alex Rivera | Logout

Why do we refactor?

Asked 2009-05-06T09:15:11.047
9

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.

Edit
Report

3 Answers

6

You may need to refactor if your code is

  • Inefficient
  • Buggy
  • Hard to extend
  • Hard to maintain

It all boils down to the original code not being very good, so you improve it. If you have reasonable unit tests it shouldn't be dangerous at all.

answered 2009-05-06T09:20:54.963
0

I refactor because:

  1. Often my code is far from optimal first time around.
  2. Hindsight is often 20-20.
  3. My code will be easier to maintain for the next guy.
  4. I have professional pride in the work I leave behind.
  5. I believe time spent now can save a lot more time (and money) further down the track.
answered 2009-05-06T09:21:17.053
0

There is a difference between large refactorings (restructuring modules, class hierarchies, interfaces) and "unit" refactorings - within methods and classes.

Whenever I touch a piece of code I do a unit refactoring - renaming variables, extracting methods; because actually seeing the code in front of me gives me more information to make it better. Sometimes refactoring also helps me to better understand what the code is doing. It's like writing or painting, you extract a fuzzy idea out of your head; put a rough skeleton onto paper; then into code. You then refine the rough idea in the code.

With modern refactoring tools like ReSharper in C#, this kind of unit refactoring is extremely easy, quick & low risk.

Large refactorings are harder, break more things, and require communication with your team members. It will become clear to everyone when these need to happen - because requirements have changed so much that the original design no longer works - and then they should be planned like a new feature.

My last rule - only refactor code that you are actually working on. If code's functionality doesn't need to be changed, then it's good enough & doesn't need further work.

Avoid refactoring just for refactoring's sake; that's just refactorbating!

answered 2009-05-06T10:46:32.090

Your Answer