tags:

views:

102

answers:

5

I have a legacy class that is rahter complex to maintain:

class OldClass {
  method1(arg1, arg2) {
      ... 200 lines of code ... 
  }

  method2(arg1) {
      ... 200 lines of code ... 
  }

  ...

  method20(arg1, arg2, arg3) {
      ... 200 lines of code ... 
  }    
}

methods are huge, unstructured and repetitive (developer loved copy/paste aprroach). I want to split each method into 3-5 small functions, whith one pulic method and several helpers.

What will you suggest? Several ideas come to my mind:

  • Add several private helper methods to each method and join them in #region (straight-forward refactoring)

  • Use Command pattern (one command class per OldClass method in a separate file).

  • Create helper static class per method with one public method & several private helper methods. OldClass methods delegate implementation to appropriate static class (very similiar to commands).

  • ?

Thank you in advance!

A: 

I would start by finding the bits that are repetitive and extracting them into helper functions. Once you've narrowed the code base down in this way, you can consider other ways to refactor, and the code will be much easier to wrap your head around.

VeeArr
Yes, it's exactly what i'm doing right now :)
Andrew Florko
A: 

DRY - Don't repeat yourself.

The first thing I always do is to remove (all) repetition. Even a single line is repetition.

That will normalise the code plus also give you a bunch of enhancements such as genericising the code.

griegs
+1  A: 

See SD CloneDR for a tool that can tell you what code blocks each of your methods have in common, including possible parameterizations.

Ira Baxter
It's so pity tool has no evaluation version for c# :(
Andrew Florko
There is one. Ask at the website.
Ira Baxter
+2  A: 

SRP - Single Responsibilty principle and DRY - Don't Repeat yourself

this. __curious_geek
A: 
  1. Start by mapping the current functionality and making an UML class diagram. That way you can effectively achieve DRY.

  2. Change the design to be effective and DRY, while still keeping the interface of your system as much the same as you can.

  3. Then you write unit tests for the new system, it would be better to write them for the old system as wel, but since you are probably going to change method names and arguments, the unit tests probably cannot work on both systems.

  4. Ask your manager feedback on the unit test, did you understood the functionality properly? Don't implement any new features, this will cause problems with existing systems using the code, and if you get the new design right adding new features

  5. Implement the approved system.

  6. Use default values as arguments to reduce overloading: SelectUser(int userId = 0) can be called with SelectUser();

MrFox