Details about the composition of optimization functions-PHP Tutorial

Source: Internet
Author: User
Describes in detail the composition of optimization functions. The following describes several optimization functions: 1. extractMethod (extract function) explanation: if the code of a function is found to be very long, it is very likely that this function has done a lot of things. below I will introduce several Optimization functions:

1. Extract Method (extraction function)

Explanation:

If you find that the code of a function is very long, it is very likely that this function has done a lot of things and you can find out whether there are comments in the function, comments are usually used to explain what the following code does. you can consider refining this code into an independent function.

The advantage of doing so is self-evident. it is the Single Responsibility Principle in the five basic principles of object-oriented. long functions are split into small functions, which will facilitate code reuse.

Before impulse:

 
  1. public void Print(Employee employee)
  2. {
  3. //print employee's information
  4. Console.WriteLine("Name:" + employee.Name);
  5. Console.WriteLine("Sex:" + employee.Sex);
  6. Console.WriteLine("Age:" + employee.Age);
  7. //print employee's salary
  8. Console.WriteLine("Salary:" + employee.Salary);
  9. Console.WriteLine("Bonus:" + employee.Bonus);
  10. }

After impulse:

 
  1. public void Print(Employee employee)
  2. {
  3. //print employee's information
  4. PrintInfo(employee);
  5. //print employee's salary
  6. PrintSalary(employee);
  7. }
  8. public void PrintInfo(Employee employee)
  9. {
  10. Console.WriteLine("Name:" + employee.Name);
  11. Console.WriteLine("Sex:" + employee.Sex);
  12. Console.WriteLine("Age:" + employee.Age);
  13. }
  14. public void PrintSalary(Employee employee)
  15. {
  16. Console.WriteLine("Salary:" + employee.Salary);
  17. Console.WriteLine("Bonus:" + employee.Bonus);
  18. }

2. Inline Method (Inline function)

Explanation:

Some functions are very short, with only one or two lines, and the code intent is also very obvious. in this case, you can consider killing this function and directly use the code in the function. too many methods in the object will make people feel uncomfortable. after removing unnecessary functions, the code will be more concise.

Before impulse:

 
  1. public bool IsDeserving(int score)
  2. {
  3. return IsScoreMoreThanSixty(score);
  4. }
  5. public bool IsScoreMoreThanSixty(int score)
  6. {
  7. return (score > 60);
  8. }

After impulse:

 
  1. public bool IsDeserving(int score)
  2. {
  3. return (score > 60) ;
  4. }

3. Inline Temp (Inline temporary variables)

Explanation:

If a temporary variable (Temp) is used to indicate the return value of a function, this is a good practice. however, if this temporary variable is really redundant, it will not affect the code reading after it is inline, or even this temporary variable hinders other refactoring work, it should be internalized.

The advantage of killing this temporary variable is that it reduces the length of the function and sometimes makes other refactoring work smoother.

Before impulse:

 
  1. int salary = employee.Salary;
  2. return (salary > 10000);

After impulse:

 
  1. Return (employee. Salary> 10000 );
  2. Replace Temp With Query (Replace temporary variables With queries)

Explanation:

The program has a temporary variable (Temp) used to save the computation results of an expression and Extract the computation expression (Extract) into an independent function (I .e., a Query type, replace all calls to this temporary variable with calls to the new function (Query). The new function can also be used by other functions.

The advantage is to reduce the function length and increase the code reuse rate, which facilitates further code reconstruction. note that Replace Temp With Query is often an essential step before the Extract Method, because local variables make the code not easy to Extract, therefore, you can replace them with the query type before performing similar refactoring.

The following example shows how to Replace Temp With Query. imagine that totalPrice was used in many code blocks in the function before the impulse. suddenly one day I found this function was too long and I needed to extract the code from this block into a separate function, in this way, you need to put totalPrice = price * num; into every extracted function. if the query type is used in the original function, this problem does not exist. if the Query formula has a large amount of computing, we do not recommend using Replace Temp With Query.

Before impulse:

 
  1. public double FinalPrice(double price, int num)
  2. {
  3. double totalPrice = price * num;
  4. if (totalPrice > 100)
  5. return totalPrice * 0.8;
  6. else
  7. return totalPrice * 0.9;
  8. }

After impulse:

 
  1. public double FinalPrice(double price, int num)
  2. {
  3. if (TotalPrice(price, num) > 100)
  4. return TotalPrice(price, num) * 0.8;
  5. else
  6. return TotalPrice(price, num) * 0.9;
  7. }
  8. public double TotalPrice(double price, int num)
  9. {
  10. return price * num;
  11. }

5. Introduce Explaining Variable (Introduce understandable variables)

Explanation:

Many times, in conditional logical expressions, many conditions are difficult to understand. why do we need to satisfy these conditions? Unclear. you can use Introduce Explaining Variable to extract each condition clause and use an appropriate temporary Variable name to indicate the meaning of the condition clause.

The advantage is that it increases the readability of the program.

Before impulse:

 
  1. if((operateSystem.Contains("Windows"))&& (browser.Contatins("IE")))
  2. {
  3. //do something
  4. }

After impulse:

 
  1. bool isWindowsOS = operateSystem.Contains("Windows");
  2. bool isIEBrowser = browser.Contatins("IE");
  3. if (isWindowsOS && isIEBrowser)
  4. {
  5. //do something
  6. }

6. Split Temporary Variable (clear Temporary variables)

Explanation:

For example, there is a temporary variable in the code that represents the rectangular perimeter somewhere in the function, and is assigned an area under the function, that is, the temporary variable is assigned more than once and not the same amount. assign an independent temporary variable for each assignment.

A variable must represent only one amount. Otherwise, the code reader may be confused.

Before impulse:

 
  1. double temp = (width + height) * 2;
  2. //do something
  3. temp = width * height;
  4. //do something

After impulse:

 
  1. double perimeter = (width + height) * 2;
  2. //do something
  3. double area = width * height;
  4. //do something

7. Remove Assignments to Parameters (Remove the parameter assignment operation)

Explanation:

The input parameters are divided into two types: "Pass value" and "transfer address". if it is "transfer address", it is understandable to change the parameter value in the function, because we just want to change the original value. however, if it is "pass value", assigning values to parameters in the code will be confusing. therefore, a temporary variable should be used in the function to replace this parameter, and other values should be assigned to this temporary variable.

Before impulse:

 
  1. public double FinalPrice(double price, int num)
  2. {
  3. price = price * num;
  4. //other calculation with price
  5. return price;
  6. }

After impulse:

 
  1. public double FinalPrice(double price, int num)
  2. {
  3. double finalPrice = price * num;
  4. //other calculation with finalPrice
  5. return finalPrice;
  6. }

8. Replace Method with Method Object (Replace functions with function objects)

Explanation:

After writing a line of code, I suddenly found that this function has become very large, and because this function contains many local variables, it cannot use Extract Method, in this case, Replace Method with Method Object is effective. the method is to put this function into a separate object, and the temporary variable in the function becomes the field in this object ).

Before impulse:

 
  1. class Bill
  2. {
  3. public double FinalPrice()
  4. {
  5. double primaryPrice;
  6. double secondaryPrice;
  7. double teriaryPrice;
  8. //long computation
  9. ...
  10. }
  11. }

After impulse:

 
  1. class Bill
  2. {
  3. public double FinalPrice()
  4. {
  5. return new PriceCalculator(this).compute();
  6. }
  7. }
  8. class PriceCalculator
  9. {
  10. double primaryPrice;
  11. double secondaryPrice;
  12. double teriaryPrice;
  13. public PriceCalculator(Bill bill)
  14. {
  15. //initial
  16. }
  17. public double compute()
  18. {
  19. //computation
  20. }
  21. }

9. Substitute Algorithm (replacement Algorithm)

Explanation:

There is such a joke:

In a multinational Daily Chemical Company, the soap production line may leak soap packets during packaging. it is certainly not allowed to sell empty soap boxes to customers, as a result, the company's president ordered a doctor-led expert group to tackle the problem. The R & D team used the world's top-notch technologies (such as infrared detection and laser radiation ), after spending a lot of dollars and half a year, I finally completed the soap box detection system. after detecting an empty soap box, the robot will release the empty box. this method effectively reduces the empty filling rate of the soap box to less than 5%, and the problem is basically solved.

A soap company in a township also encountered a similar problem. The Boss ordered the assembly line foreman who graduated from junior high school to find a solution. after half a day of thinking, the foreman took an electric fan to the end of the production line and blew it against the conveyor belt. the soap boxes without soap were blown down by the wind because they were light...

This joke can be a good explanation of Substitute Algorithm. for complex algorithms in functions, try to simplify this Algorithm to achieve the same or even better effect as before.

Link to this article:

Explain optimization function: 1. Extract Method (Extract function) explanation: if the code of a function is found to be very long, it is very likely that this function has done a lot of things, find...

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.