Replace Method with Method Object
Overview
Put this function into a separate object, so that the local variable becomes the value field in the object, and then you can break down this large function into several small functions in the same object.
Motivation)
Small functions are attractive. As long as the relatively independent code is extracted from large functions, the code readability can be greatly improved.
Example
public int Gamma(int inputValue, int quantity, int yearToDate) { int importantValue1 = inputValue * quantity + DateTime.Now.Minute; int importantValue2 = inputValue * yearToDate + 100; if ((yearToDate - importantValue1) > 100) importantValue2 -= 20; int importantValue3 = importantValue2 * 7; return importantValue3 - 2 * importantValue1; }
Change
private int importantValue1; private int importantValue2; private int importantValue3; public int Gamma(int inputValue, int quantity, int yearToDate) { importantValue1 = inputValue * quantity + DateTime.Now.Minute; importantValue2 = inputValue * yearToDate + 100; ImportantThing(yearToDate); importantValue3 = importantValue2 * 7; return importantValue3 - 2 * importantValue1; } private void ImportantThing(int yearToDate) { if ((yearToDate - importantValue1) > 100) importantValue2 -= 20; }
Substitute Algorithm (replace your Algorithm)
Overview
Replace the method body with another algorithm.
Motivation)
If you find that there is a clearer way to do one thing, you should replace the complicated way in a clearer way. Some complicated things can be broken down into simple small pieces, but sometimes you have to break the wrist and delete the entire algorithm to replace it with a simpler algorithm.
Example
public string FoundPerson(string[] people) { for (int i = 0; i < people.Length; i++) { if (people[i].Equals("Don")) { return "Don"; } if (people[i].Equals("John")) { return "John"; } if (people[i].Equals("Kent")) { return "Kent"; } } return ""; }
Change
public string FoundPerson(string[] people) { List<string> candidates = new List<string>() { "Don", "John", "Kent" }; for (int i = 0; i < people.Length; i++) { if (candidates.Contains(people[i])) return people[i]; } return ""; }