Home Backend Development PHP Tutorial Detailed introduction to the composition of optimization functions_PHP tutorial

Detailed introduction to the composition of optimization functions_PHP tutorial

Jul 20, 2016 am 10:57 AM
extract method under introduce optimization several kinds function Discover constitute of explain detailed

The following introduces several optimization functions:

1. Extract Method (extract function)

Explanation:

If you find that the code of a function is very long, it is most likely that this function does a lot of things. Look for comments in the function. Comments are often meant to explain what the following piece of code does. You can consider refining (Extract) this piece of code into an independent function.

The benefits of this are self-evident. It is the Single Responsibility Principle (Single Responsibility Principle) among the five basic principles of object-oriented, which is relatively long. The function is split into small functions, which will help the code to be reused.

Before the impulse:

<ol class="dp-c">
<li class="alt"><span><span class="keyword">public</span><span> void Print(Employee employee)   </span></span></li>
<li><span>{   </span></li>
<li class="alt">
<span class="comment">//print employee's information  </span><span> </span>
</li>
<li>
<span>Console.WriteLine(</span><span class="string">"Name:"</span><span> + employee.Name);   </span>
</li>
<li class="alt">
<span>Console.WriteLine(</span><span class="string">"Sex:"</span><span> + employee.Sex);   </span>
</li>
<li>
<span>Console.WriteLine(</span><span class="string">"Age:"</span><span> + employee.Age);   </span>
</li>
<li class="alt">
<span class="comment">//print employee's salary  </span><span> </span>
</li>
<li>
<span>Console.WriteLine(</span><span class="string">"Salary:"</span><span> + employee.Salary);   </span>
</li>
<li class="alt">
<span>Console.WriteLine(</span><span class="string">"Bonus:"</span><span> + employee.Bonus);   </span>
</li>
<li><span>}  </span></li>
</ol>
Copy after login

After the impulse:

<ol class="dp-c">
<li class="alt"><span><span class="keyword">public</span><span> void Print(Employee employee)   </span></span></li>
<li><span>{   </span></li>
<li class="alt">
<span class="comment">//print employee's information  </span><span> </span>
</li>
<li><span>PrintInfo(employee);   </span></li>
<li class="alt">
<span class="comment">//print employee's salary  </span><span> </span>
</li>
<li><span>PrintSalary(employee);   </span></li>
<li class="alt"><span>}   </span></li>
<li>
<span class="keyword">public</span><span> void PrintInfo(Employee employee)   </span>
</li>
<li class="alt"><span>{   </span></li>
<li>
<span>Console.WriteLine(</span><span class="string">"Name:"</span><span> + employee.Name);   </span>
</li>
<li class="alt">
<span>Console.WriteLine(</span><span class="string">"Sex:"</span><span> + employee.Sex);   </span>
</li>
<li>
<span>Console.WriteLine(</span><span class="string">"Age:"</span><span> + employee.Age);   </span>
</li>
<li class="alt"><span>}   </span></li>
<li>
<span class="keyword">public</span><span> void PrintSalary(Employee employee)   </span>
</li>
<li class="alt"><span>{   </span></li>
<li>
<span>Console.WriteLine(</span><span class="string">"Salary:"</span><span> + employee.Salary);   </span>
</li>
<li class="alt">
<span>Console.WriteLine(</span><span class="string">"Bonus:"</span><span> + employee.Bonus);   </span>
</li>
<li><span>}  </span></li>
</ol>
Copy after login

2. Inline Method

Explanation:

Some functions are very short, only one or two lines, and the intention of the code is also very obvious, At this time, you can consider killing this function and using the code in the function directly. Too many methods in the object will make people feel uncomfortable. After killing completely unnecessary functions, the code will be more concise.

Before impulse:

<ol class="dp-c">
<li class="alt"><span><span class="keyword">public</span><span> bool IsDeserving(int score)   </span></span></li>
<li><span>{   </span></li>
<li class="alt">
<span class="keyword">return</span><span> IsScoreMoreThanSixty(score);   </span>
</li>
<li><span>}   </span></li>
<li class="alt">
<span class="keyword">public</span><span> bool IsScoreMoreThanSixty(int score)   </span>
</li>
<li><span>{   </span></li>
<li class="alt">
<span class="keyword">return</span><span> (score > 60);   </span>
</li>
<li><span>}  </span></li>
</ol>
Copy after login

After impulse:

<ol class="dp-c">
<li class="alt"><span><span class="keyword">public</span><span> bool IsDeserving(int score)   </span></span></li>
<li><span>{   </span></li>
<li class="alt">
<span class="keyword">return</span><span> (score > 60) ;   </span>
</li>
<li><span>}  </span></li>
</ol>
Copy after login

3. Inline Temp (inline temporary variables)

Explanation:

If there is a temporary variable (Temp) used to represent the return value of a function, generally speaking, this approach is good. But if this temporary variable is really redundant, there is no need to inline the temporary variable. If it does not affect the reading of the code, or even if this temporary variable hinders other refactoring work, this temporary variable should be inlined.

The advantage of getting rid of this temporary variable is that it reduces the length of the function, and sometimes it can be Other reconstruction work proceeds more smoothly.

Before the impulse:

<ol class="dp-c">
<li class="alt"><span><span>int salary = employee.Salary;   </span></span></li>
<li>
<span class="keyword">return</span><span> (salary > 10000);  </span>
</li>
</ol>
Copy after login

After the impulse:

<ol class="dp-c">
<li class="alt"><span><span class="keyword">return</span><span> (employee.Salary > 10000);   </span></span></li>
<li><span>Replace Temp With Query (用查询式代替临时变量) </span></li>
</ol>
Copy after login

Explanation:

There are A temporary variable (Temp) is used to save the calculation result of a certain expression. Extract the calculation expression into an independent function (i.e. Query), and replace all the places where this temporary variable is called with When calling a new function (Query), the new function can also be used by other functions.

The advantage is to reduce the length of the function, increase the code reuse rate, and facilitate further code reconstruction. And pay attention to Replace Temp With Query It is often an essential step before Extract Method, because local variables will make the code less easy to extract, so they can be replaced with query formulas before similar reconstruction.

The following example is not It is necessary to use Replace Temp With Query, which mainly shows how to Replace Temp With Query. Imagine that there are many code blocks in the "impulse before" function that use totalPrice. Suddenly one day I found that this function is too long, and I need to block this block. The code is refined into a separate function, so totalPrice = price * num; needs to be put into each extracted function. If the query formula is used in the original function, this problem does not exist. If the query formula The calculation is very heavy, and it is not recommended to use Replace Temp With Query.

Before impulse:

<ol class="dp-c">
<li class="alt"><span><span class="keyword">public</span><span> double FinalPrice(double price, int num)   </span></span></li>
<li><span>{   </span></li>
<li class="alt"><span>double totalPrice = price * num;   </span></li>
<li>
<span class="keyword">if</span><span> (totalPrice > 100)   </span>
</li>
<li class="alt">
<span class="keyword">return</span><span> totalPrice * 0.8;   </span>
</li>
<li>
<span class="keyword">else</span><span>   </span>
</li>
<li class="alt">
<span class="keyword">return</span><span> totalPrice * 0.9;   </span>
</li>
<li><span>}  </span></li>
</ol>
Copy after login

After impulse:

<ol class="dp-c">
<li class="alt"><span><span class="keyword">public</span><span> double FinalPrice(double price, int num)   </span></span></li>
<li><span>{   </span></li>
<li class="alt">
<span class="keyword">if</span><span> (TotalPrice(price, num) > 100)   </span>
</li>
<li>
<span class="keyword">return</span><span> TotalPrice(price, num) * 0.8;   </span>
</li>
<li class="alt">
<span class="keyword">else</span><span>   </span>
</li>
<li>
<span class="keyword">return</span><span> TotalPrice(price, num) * 0.9;   </span>
</li>
<li class="alt"><span>}   </span></li>
<li>
<span class="keyword">public</span><span> double TotalPrice(double price, int num)   </span>
</li>
<li class="alt"><span>{   </span></li>
<li>
<span class="keyword">return</span><span> price * num;   </span>
</li>
<li class="alt"><span>}  </span></li>
</ol>
Copy after login

5. Introduce Explaining Variable (introducing understandable variables)

Explanation:

Many times in conditional logical expressions, many conditions make it difficult to understand its meaning. Why? Satisfy this condition? Not sure. You can use Introduce Explaining Variable to extract each conditional clause, and use an appropriate temporary variable name to express the meaning of the conditional clause.

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

Before impulse:

<ol class="dp-c">
<li class="alt"><span><span class="keyword">if</span><span>((operateSystem.Contains(</span><span class="string">"Windows"</span><span>))&&   (browser.Contatins(</span><span class="string">"IE"</span><span>)))     </span></span></li>
<li><span>{    </span></li>
<li class="alt">
<span> </span><span class="comment">//do something   </span><span> </span>
</li>
<li><span>} </span></li>
</ol>
Copy after login

After impulse:

<ol class="dp-c">
<li class="alt"><span><span>bool isWindowsOS = operateSystem.Contains(</span><span class="string">"Windows"</span><span>);   </span></span></li>
<li>
<span>bool isIEBrowser = browser.Contatins(</span><span class="string">"IE"</span><span>);   </span>
</li>
<li class="alt">
<span class="keyword">if</span><span> (isWindowsOS && isIEBrowser)   </span>
</li>
<li><span>{   </span></li>
<li class="alt">
<span class="comment">//do something  </span><span> </span>
</li>
<li><span>}  </span></li>
</ol>
Copy after login

6. Split Temporary Variable Variable)

Explanation:

For example, there is a temporary variable in the code that represents the perimeter of the rectangle somewhere above the function, and is assigned the area below the function, which is this temporary variable The variable is assigned more than once and does not represent the same quantity. An independent temporary variable should be allocated for each assignment.

A variable should only represent one quantity, otherwise it will confuse code readers .

Before impulse:

<ol class="dp-c">
<li class="alt"><span><span>double temp = (width + height) * 2;   </span></span></li>
<li>
<span class="comment">//do something  </span><span> </span>
</li>
<li class="alt"><span>temp = width * height;   </span></li>
<li>
<span class="comment">//do something </span><span> </span>
</li>
</ol>
Copy after login

After impulse:

<ol class="dp-c">
<li class="alt"><span><span>double perimeter = (width + height) * 2;   </span></span></li>
<li>
<span class="comment">//do something  </span><span> </span>
</li>
<li class="alt"><span>double area = width * height;   </span></li>
<li>
<span class="comment">//do something </span><span> </span>
</li>
</ol>
Copy after login

7. Remove Assignments to Parameters (eliminate assignment operations to parameters)

Explanation:

There are two types of incoming parameters: "passing by value" and "passing by address". If it is "passing by address", there is nothing wrong with changing the value of the parameter in the function, because we are I want to change the original value. But if it is "pass by value" and assigning a value to the parameter in the code, it will cause confusion. Therefore, you should use a temporary variable to replace the parameter in the function, and then perform other assignment operations on this temporary variable. .

Before impulse:

<ol class="dp-c">
<li class="alt"><span><span class="keyword">public</span><span> double FinalPrice(double price, int num)   </span></span></li>
<li><span>{   </span></li>
<li class="alt"><span>price = price * num;   </span></li>
<li>
<span class="comment">//other calculation with price  </span><span> </span>
</li>
<li class="alt">
<span class="keyword">return</span><span> price;   </span>
</li>
<li><span>}  </span></li>
</ol>
Copy after login

After impulse:

<ol class="dp-c">
<li class="alt"><span><span class="keyword">public</span><span> double FinalPrice(double price, int num)   </span></span></li>
<li><span>{   </span></li>
<li class="alt"><span>double finalPrice = price * num;   </span></li>
<li>
<span class="comment">//other calculation with finalPrice  </span><span> </span>
</li>
<li class="alt">
<span class="keyword">return</span><span> finalPrice;   </span>
</li>
<li><span>}  </span></li>
</ol>
Copy after login

8. Replace Method with Method Object (replace function with function object)

Explanation:

After impulsively writing down lines of code, I suddenly found that this function became very large, and because this function contained many local variables, it was impossible to use Extract Method. This Replace Method with Method Object plays a killer role. The method is to put this function into a separate object, and the temporary variables in the function become the value fields (fields) in this object.

Before impulse:

<ol class="dp-c">
<li class="alt"><span><span class="keyword">class</span><span> Bill   </span></span></li>
<li><span>{   </span></li>
<li class="alt">
<span class="keyword">public</span><span> double FinalPrice()   </span>
</li>
<li><span>{   </span></li>
<li class="alt"><span>double primaryPrice;   </span></li>
<li><span>double secondaryPrice;   </span></li>
<li class="alt"><span>double teriaryPrice;   </span></li>
<li>
<span class="comment">//long computation  </span><span> </span>
</li>
<li class="alt"><span>...   </span></li>
<li><span>}   </span></li>
<li class="alt"><span>}  </span></li>
</ol>
Copy after login

After impulse:

<ol class="dp-c">
<li class="alt"><span><span class="keyword">class</span><span> Bill   </span></span></li>
<li><span>{   </span></li>
<li class="alt">
<span class="keyword">public</span><span> double FinalPrice()   </span>
</li>
<li><span>{   </span></li>
<li class="alt">
<span class="keyword">return</span><span> </span><span class="keyword">new</span><span> PriceCalculator(this).compute();   </span>
</li>
<li><span>}   </span></li>
<li class="alt"><span>}   </span></li>
<li>
<span class="keyword">class</span><span> PriceCalculator   </span>
</li>
<li class="alt"><span>{   </span></li>
<li><span>double primaryPrice;   </span></li>
<li class="alt"><span>double secondaryPrice;   </span></li>
<li><span>double teriaryPrice;   </span></li>
<li class="alt">
<span class="keyword">public</span><span> PriceCalculator(Bill bill)   </span>
</li>
<li><span>{   </span></li>
<li class="alt">
<span class="comment">//initial  </span><span> </span>
</li>
<li><span>}   </span></li>
<li class="alt">
<span class="keyword">public</span><span> double compute()   </span>
</li>
<li><span>{   </span></li>
<li class="alt">
<span class="comment">//computation  </span><span> </span>
</li>
<li><span>}   </span></li>
<li class="alt"><span>}  </span></li>
</ol>
Copy after login

9. Substitute Algorithm (replacement algorithm)

Explanation:

There is such a joke:

For a multinational daily chemical company, there was a problem in the soap production line that soap may be missing during packaging. Empty soap boxes must not be sold to customers, so the president of the company ordered an expert group led by a doctor to be formed to tackle this problem. , the R&D team used the world's most sophisticated technologies (such as infrared detection, laser irradiation, etc.), and after spending a lot of US dollars and half a year, they finally completed the soap box detection system. After detecting the empty soap box, the robot hand The empty box will be pushed out. This method effectively reduces the empty filling rate of the soap box to less than 5%, and the problem is basically solved.

A township soap company also encountered a similar problem, and the boss ordered the assembly line of junior high school graduates The foreman tried to find a way to solve the problem. After thinking for a long time, the foreman took an electric fan to the end of the production line and blew it hard on the conveyor belt. The soap boxes that were not filled with soap were blown down by the wind due to their light weight...

This joke can be a good explanation of Substitute Algorithm. For complex algorithms in functions, try to find ways to simplify the algorithm to achieve the same or even better results than before.

Link to this article:

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/445784.htmlTechArticleThe following introduces several optimization functions: 1. Extract Method (extract function) Explanation: If the code of a function is found Very long, a very likely situation is that this function does a lot of things, find...
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Tips for dynamically creating new functions in golang functions Tips for dynamically creating new functions in golang functions Apr 25, 2024 pm 02:39 PM

Go language provides two dynamic function creation technologies: closure and reflection. closures allow access to variables within the closure scope, and reflection can create new functions using the FuncOf function. These technologies are useful in customizing HTTP routers, implementing highly customizable systems, and building pluggable components.

Considerations for parameter order in C++ function naming Considerations for parameter order in C++ function naming Apr 24, 2024 pm 04:21 PM

In C++ function naming, it is crucial to consider parameter order to improve readability, reduce errors, and facilitate refactoring. Common parameter order conventions include: action-object, object-action, semantic meaning, and standard library compliance. The optimal order depends on the purpose of the function, parameter types, potential confusion, and language conventions.

How to write efficient and maintainable functions in Java? How to write efficient and maintainable functions in Java? Apr 24, 2024 am 11:33 AM

The key to writing efficient and maintainable Java functions is: keep it simple. Use meaningful naming. Handle special situations. Use appropriate visibility.

Complete collection of excel function formulas Complete collection of excel function formulas May 07, 2024 pm 12:04 PM

1. The SUM function is used to sum the numbers in a column or a group of cells, for example: =SUM(A1:J10). 2. The AVERAGE function is used to calculate the average of the numbers in a column or a group of cells, for example: =AVERAGE(A1:A10). 3. COUNT function, used to count the number of numbers or text in a column or a group of cells, for example: =COUNT(A1:A10) 4. IF function, used to make logical judgments based on specified conditions and return the corresponding result.

C++ program optimization: time complexity reduction techniques C++ program optimization: time complexity reduction techniques Jun 01, 2024 am 11:19 AM

Time complexity measures the execution time of an algorithm relative to the size of the input. Tips for reducing the time complexity of C++ programs include: choosing appropriate containers (such as vector, list) to optimize data storage and management. Utilize efficient algorithms such as quick sort to reduce computation time. Eliminate multiple operations to reduce double counting. Use conditional branches to avoid unnecessary calculations. Optimize linear search by using faster algorithms such as binary search.

Detailed introduction of Samsung S24ai functions Detailed introduction of Samsung S24ai functions Jun 24, 2024 am 11:18 AM

2024 is the first year of AI mobile phones. More and more mobile phones integrate multiple AI functions. Empowered by AI smart technology, our mobile phones can be used more efficiently and conveniently. Recently, the Galaxy S24 series released at the beginning of the year has once again improved its generative AI experience. Let’s take a look at the detailed function introduction below. 1. Generative AI deeply empowers Samsung Galaxy S24 series, which is empowered by Galaxy AI and brings many intelligent applications. These functions are deeply integrated with Samsung One UI6.1, allowing users to have a convenient intelligent experience at any time, significantly improving the performance of mobile phones. Efficiency and convenience of use. The instant search function pioneered by the Galaxy S24 series is one of the highlights. Users only need to press and hold

C++ Function Exception Advanced: Customized Error Handling C++ Function Exception Advanced: Customized Error Handling May 01, 2024 pm 06:39 PM

Exception handling in C++ can be enhanced through custom exception classes that provide specific error messages, contextual information, and perform custom actions based on the error type. Define an exception class inherited from std::exception to provide specific error information. Use the throw keyword to throw a custom exception. Use dynamic_cast in a try-catch block to convert the caught exception to a custom exception type. In the actual case, the open_file function throws a FileNotFoundException exception. Catching and handling the exception can provide a more specific error message.

Introduction to the online score checking platform (convenient and fast score query tool) Introduction to the online score checking platform (convenient and fast score query tool) Apr 30, 2024 pm 08:19 PM

A fast score query tool provides students and parents with more convenience. With the development of the Internet, more and more educational institutions and schools have begun to provide online score check services. To allow you to easily keep track of your child's academic progress, this article will introduce several commonly used online score checking platforms. 1. Convenience - Parents can check their children's test scores anytime and anywhere through the online score checking platform. Parents can conveniently check their children's test scores at any time by logging in to the corresponding online score checking platform on a computer or mobile phone. As long as there is an Internet connection, whether at work or when going out, parents can keep abreast of their children's learning status and provide targeted guidance and help to their children. 2. Multiple functions - in addition to score query, it also provides information such as course schedules and exam arrangements. Many online searches are available.

See all articles