Jakub Arnold
Jakub Arnold

Reputation: 87230

Refactoring legacy code

I'm working on a quite large legacy Rails app. Most of the code is downright horrible, and I'm trying to make it better as I go through it.

The problem is, there are no tests, and almost everything is wrong. So far I've went through the code and made a lot of handwritten notes on stuff that needs to be refactored, so that I can later do it when I get to adding tests.

But there are things that are just so simple and scream for quick refactoring. For example:

def isValid(valid)
    name = Long::AndUglyModule::UglyClass.getvalid(valid)
    return name
end

the whole class looks like this, which makes me wanna just rewrite it to

include Long::AndUglyModule

def is_valid(valid)
  UglyClass.getvalid(valid)
end

the problem is, that I'm afraid of introducing some subtle mistakes. On the other hand, working with code that looks like this gives me loads of headaches.

Is it better to just do simple refactorings instantly, or leave the code as it is until I actually have to work with it or change it directly?

Upvotes: 2

Views: 565

Answers (1)

Joop Eggen
Joop Eggen

Reputation: 109597

I have much experience with huge legacy code and entire refactoring.

  • Allow a hybrid of new and old.
  • Clearly separate both code bases.
  • Log exceptions.
  • Making the old code more beautiful can be a 10000% waste of time.
  • Refactor first where it makes sense: remove HTML framesets, declarative navigation. Small functions for cumbersome constructs.
  • Make a source processing app, translating antipattern in the code to better code. Multisource regex find and replacements are needed too, \1 for recognizing a repetition.
  • Introduce methods where the old code was too long.
  • Shrink code: copied & edited pieces to a business logic class keeping all together.
  • Process source wise.

Before all: start with statistics, KB, number of lines, percentage processed, time line. With a google spread sheet one can communicate the progress, and calculate the end date. That legacy code takes much time is underestimated, so be sure you have good documentation.

There is much more to say, but this is what immediately relates to "small refactoring."

Conclusion:

One really cannot and should not do anything against the inherent urge of a programmer to refactor small pieces, but refactoring should either be a conversion over multiple sources and occurrences, or while a single use-case is corrected or redesigned.

Upvotes: 2

Related Questions