Refactoring can break down complex things into simple pieces. But sometimes you have to cut off the whole algorithm and replace it with a simple algorithm, and if you find that there is a clearer way to do something, you have every reason to solve the problem in a clearer way. If you start using libraries and find that the features in the library are duplicated with your code, you should also change your original algorithm. Or when you want to modify the original algorithm, let him do something slightly different from the original, then you can also replace the original algorithm with a more easily modified algorithm, let the subsequent changes to the simple point.
Before using this technique, make sure you fully understand the original function, replace the large and complex algorithm is very complex, you can use Extract method to decompose him into a simple small function, you can be sure of the algorithm to replace the work.
Practice:
- Get ready for another replacement algorithm and let him compile.
- For existing tests, execute the new algorithm above, and if the result is exactly the same as the original result, the refactoring ends.
- If the test results are different, the old algorithm is used as the reference standard. Perform the new and old algorithms separately for each test case, and observe which test cases are problematic and the problems you are experiencing.
Example:
QString Findperson (qstringlist person) { for(inti =0; I < Person.count (); ++i) {if(person.at (i) = ="Don") return "Don"; Else if(person.at (i) = ="John") return "John"; Else if(person.at (i) = ="Kent") return "Kent"; } return "";}
Find this need to modify the internal algorithm, we prepared a different algorithm, then compile the test, and then replace
QString Findperson (qstringlist person) {qstringlist perlist= Qstringlist () <<"Don"<<"John"<<"Kent"; for(inti =0;intI < Person.count (); ++inti) {if(Perlist.contains (person.at (i)))returnperson.at (i); } return "";}
After passing the test case, we can determine that we have completed the reconstruction of the algorithm substitution.
Refactoring-Improving the design of existing code reading notes----substitute algorithm