search
HomeBackend DevelopmentPHP TutorialDetailed 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
extractmethodunderintroduceoptimizationseveral kindsfunctionDiscoverconstituteofexplaindetailed

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>

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>

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>

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>

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>

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>

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>

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>

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>

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>

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>

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>

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>

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>

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>

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>

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
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
The Continued Use of PHP: Reasons for Its EnduranceThe Continued Use of PHP: Reasons for Its EnduranceApr 19, 2025 am 12:23 AM

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

PHP and Python: Exploring Their Similarities and DifferencesPHP and Python: Exploring Their Similarities and DifferencesApr 19, 2025 am 12:21 AM

PHP and Python are both high-level programming languages ​​that are widely used in web development, data processing and automation tasks. 1.PHP is often used to build dynamic websites and content management systems, while Python is often used to build web frameworks and data science. 2.PHP uses echo to output content, Python uses print. 3. Both support object-oriented programming, but the syntax and keywords are different. 4. PHP supports weak type conversion, while Python is more stringent. 5. PHP performance optimization includes using OPcache and asynchronous programming, while Python uses cProfile and asynchronous programming.

PHP and Python: Different Paradigms ExplainedPHP and Python: Different Paradigms ExplainedApr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP and Python: A Deep Dive into Their HistoryPHP and Python: A Deep Dive into Their HistoryApr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Choosing Between PHP and Python: A GuideChoosing Between PHP and Python: A GuideApr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Frameworks: Modernizing the LanguagePHP and Frameworks: Modernizing the LanguageApr 18, 2025 am 12:14 AM

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHP's Impact: Web Development and BeyondPHP's Impact: Web Development and BeyondApr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

How does PHP type hinting work, including scalar types, return types, union types, and nullable types?How does PHP type hinting work, including scalar types, return types, union types, and nullable types?Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

See all articles

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

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment