Monday, June 2, 2008

Refactor To Make Immediate Change Easier

Jeremy Miller gives his reasons for refactoring.  He gives two over-arching reasons.  The first is "To remedy a deficiency in code, design, or architectural quality" and the second, "To make a forthcoming change to the code easier."  I'm very much in agreement with the second, but the first makes me nervous.  Refactoring is not an end to itself.  Changing code to make it of higher quality without an immediate purpose in mind strikes me as wasteful.  Code doesn't need to be pretty until it is being maintained.  The compiler doesn't care how ugly the code is.  The reason to make code of higher quality is because someone will may have to change that code and it will be hard to change in its low-quality state.  However, if change is not imminent, cleaning up the code now is a non-optimal decision.  Suppose the code continues working and no change is necessary in that part of the code base.  Because the compiler doesn't care and no human looks at it, the effort to make it higher quality is wasted.  Instead, it is better to wait until the change is needed to make the updates.  This would seem to be in line with the Lean principle of waiting until the last responsible moment or just in time delivery.  It is better to wait than to refactor pre-emptively.  Refactoring can become a yak-shaving exercise if one is not careful.  To be fair, Jeremy does end with this advice:  "If a structural problem in the code isn't causing any immediate harm or friction, you probably leave it alone for now."

3 comments:

  1. It would seem to me to be that in a sufficiently long time-line, all code must be maintained (unless it's trivial), and a refactor, if done, is best done by someone who's familiar with the code.  The further you get from that code's inception, the less likely it's going to be that anyone really understands it, which nets two problems.  The first is the higher probability of breaking something, and the second is time investment required to understand what it does (risk and cost both go up).
    Now, I have a pretty high bar for what constitutes architecture bad enough to require refactor, but it seems to me that if the code is highly likely to be a problem, even if that's 3 years from now, it's best to fix it as early as possible.  Otherwise it becomes a land-mine for somebody to find when it does break.

    ReplyDelete
  2. "the compiler doesn't care"
    For those of us that program primarily in Dynamic languages, refactoring to improve code quality is a valid reason. The interpreter cares a lot more about ugly code than the compiler.
    Kevin

    ReplyDelete
  3. I believe it was Martin Fowler who put forth the maxim that if a proposed change is hard, refactor until it becomes easy.
    I also like to refactor big functions into small functions, big classes into small classes, etc.  This is usually the type of refactorings needed to make hard changes easier.

    ReplyDelete