9

Possible Duplicate:
I’ve inherited 200K lines of spaghetti code — what now?

I'm dealing with legacy code. It contains some BIG classes (line count 8000+) and some BIG methods (line count 3000+). For one of these methods I wrote a unit test that covers at least some code. This function has no specific structure, it is a mess of nested loops and conditions. I'd like to refactor but still I have no idea how to start.

I actually started by extracting one single function. In the end it had to have 21 parameters :-/

Should I ...
1. continue extracting awful functions knowing that in the long run I will succeed?
2. start extracting even bigger functions? So I expose the structure of this monster and then I can start the real refactoring.
3. only extract small "good" functions (and / or classes) just because I am a helluva clean coder?
4. do something completely different?

TobiMcNamobi
  • 1,171

2 Answers2

6

Refactoring is somewhat the whole books is written about. It's hard to retell all the methods and pitfalls.

  1. Before starting refactoring write the tests for a piece you want to refactor.
  2. Start refactoring with small and clean pieces of those big functions
  3. Find the piece that can be rewritten as a function and make it a function.
  4. Run tests to be sure you've done the things right and no side effects appears

After this you should have and idea what has to be done with all other (big one) pieces. When the whole thing becomes clearer then you can make a higher-level redesign.

P.S. it's just a brief sketch. About refactoring itself is better to read some books (like M. Fowler - Refactoring, etc.)

maverik
  • 184
3

Code Complete recommends creating an interface or a wrapper between the legacy code and new code that uses it. Keep the interface clean and as you need to make changes to the legacy code, refactor or rewrite the pieces that you need to and move them forward.

If you need to make enough changes, then eventually the classes will be brought up to par with new code.

CLandry
  • 187