Refactoring. Your way to reduce code complexity of big class with big methods
I have a legacy class that is rather complex to maintain:
class OldClass {
method1(arg1, arg2) {
... 200 lines of code ...
}开发者_如何学Python
method2(arg1) {
... 200 lines of code ...
}
...
method20(arg1, arg2, arg3) {
... 200 lines of code ...
}
}
The methods are huge, unstructured, and repetitive (developer loved copy/paste aprroach). I want to split each method into 3-5 small functions, with one pulic method and several helpers.
What would 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!
SRP - Single Responsibilty principle and DRY - Don't Repeat yourself
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.
See SD CloneDR for a tool that can tell you what code blocks each of your methods have in common, including possible parameterizations.
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.
Start by mapping the current functionality and making an UML class diagram. That way you can effectively achieve DRY.
Change the design to be effective and DRY, while still keeping the interface of your system as much the same as you can.
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.
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
Implement the approved system.
Use default values as arguments to reduce overloading:
SelectUser(int userId = 0)
can be called withSelectUser();
精彩评论