Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What are the components of Java optimization functions?

2025-04-08 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article mainly introduces the composition of the Java optimization function of what the relevant knowledge, the content is detailed and easy to understand, the operation is simple and fast, with a certain reference value, I believe you will have something to gain after reading this Java optimization function composition of the article, let's take a look.

1. Extract Method (refinement function)

Explanation:

If you find that the code of a function is very long, it is likely that the function does a lot of things. Look for comments in the function, often to explain what the following code does. Consider Extract this code into a separate function.

The benefit of this is self-evident, which is the single responsibility principle (Single Responsibility Principle) among the five basic principles of object-orientation. long functions are divided into small functions, which will facilitate code reuse.

Before impulse:

Public void Print (Employee employee) {/ / print employee's information Console.WriteLine ("Name:" + employee.Name); Console.WriteLine ("Sex:" + employee.Sex); Console.WriteLine ("Age:" + employee.Age); / / print employee's salary Console.WriteLine ("Salary:" + employee.Salary); Console.WriteLine ("Bonus:" + employee.Bonus);}

After impulse:

Public void Print (Employee employee) {/ / print employee's information PrintInfo (employee); / / print employee's salary PrintSalary (employee);} public void PrintInfo (Employee employee) {Console.WriteLine ("Name:" + employee.Name); Console.WriteLine ("Sex:" + employee.Sex); Console.WriteLine ("Age:" + employee.Age);} public void PrintSalary (Employee employee) {Console.WriteLine ("Salary:" + employee.Salary) Console.WriteLine ("Bonus:" + employee.Bonus);}

2. Inline Method (inline functions)

Explanation:

Some functions are very short, only one or two lines, and the intention of the code is very obvious, so you can consider killing this function and directly using the code in the function. Too many methods in objects can be uncomfortable, and the code will be more concise after killing completely unnecessary functions.

Before impulse:

Public bool IsDeserving (int score) {return IsScoreMoreThanSixty (score);} public bool IsScoreMoreThanSixty (int score) {return (score > 60);}

After impulse:

Public bool IsDeserving (int score) {return (score > 60);}

3. Inline Temp (inline temporary variables)

Explanation:

Generally speaking, it is good to have a temporary variable (Temp) to represent the return value of a function. But if this temporary variable is really superfluous, inlining the temporary variable does not affect the reading of the code, or even hinders other refactoring work, the temporary variable should be inlined.

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

Before impulse:

Int salary = employee.Salary; return (salary > 10000)

After impulse:

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

Explanation:

There is a temporary variable (Temp) in the program to save the evaluation results of an expression, Extract the expression into an independent function (query Query), and replace all the places where the temporary variable is called with a call to a new function (Query). The new function can also be used by other functions.

The advantage lies in reducing the length of the function and increasing the code reuse rate, which is beneficial to the further refactoring of the code. And note that Replace Temp With Query is often an essential step before Extract Method, because local variables make the code less easy to extract, so you can replace them with queries before doing similar refactoring.

The following example is not necessary to use Replace Temp With Query, mainly shows how to Replace Temp With Query. Imagine that many blocks of code in the "before impulse" function use totalPrice. Suddenly one day I find that this function is too long. I need to refine this block of code into a separate function, so I need to put totalPrice = price * num; into each extracted function. If the query form is used in the original function, this problem does not exist. If there is a large amount of computation in the query formula, it is not recommended to use Replace Temp With Query.

Before impulse:

Public double FinalPrice (double price, int num) {double totalPrice = price * num; if (totalPrice > 100) return totalPrice * 0.8; else return totalPrice * 0.9;}

After impulse:

Public double FinalPrice (double price, int num) {if (TotalPrice (price, num) > 100) return TotalPrice (price, num) * 0.8; else return TotalPrice (price, num) * 0.9;} public double TotalPrice (double price, int num) {return price * num;}

5. Introduce Explaining Variable (introduce understandable variables)

Explanation:

In many cases, in conditional logic expressions, many conditions make it difficult to understand its meaning. Why should this condition be satisfied? I don't know. You can use Introduce Explaining Variable to extract each conditional clause and use an appropriate temporary variable name to represent the meaning of the conditional clause.

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

Before impulse:

If ((operateSystem.Contains ("Windows")) & & (browser.Contatins ("IE") {/ / do something}

After impulse:

Bool isWindowsOS = operateSystem.Contains ("Windows"); bool isIEBrowser = browser.Contatins ("IE"); if (isWindowsOS & & isIEBrowser) {/ / do something}

6. Split Temporary Variable (excluding temporary variables)

Explanation:

For example, there is a temporary variable in the code that represents the perimeter of the rectangle somewhere above the function and is given an area under the function, that is, the temporary variable is assigned more than once and does not represent the same quantity. A separate temporary variable should be assigned for each assignment.

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

Before impulse:

Double temp = (width + height) * 2; / / do something temp = width * height; / / do something

After impulse:

Double perimeter = (width + height) * 2; / / do something double area = width * height; / / do something

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

Explanation:

There are two types of input parameters: "passing value" and "passing address". If it is "passing address", there is nothing wrong with changing the value of the parameter in the function, because we just want to change the original value. However, if it is passing a value, assigning a value to the parameter in the code will be confusing. So you should replace this parameter with a temporary variable in the function, and then assign other values to the temporary variable.

Before impulse:

Public double FinalPrice (double price, int num) {price = price * num; / / other calculation with price return price;}

After impulse:

Public double FinalPrice (double price, int num) {double finalPrice = price * num; / / other calculation with finalPrice return finalPrice;}

8. Replace Method with Method Object (using function objects instead of functions)

Explanation:

Impulsively write down a line of code, suddenly found that this function has become very large, and because this function contains a lot of local variables, making it impossible to use Extract Method, then Replace Method with Method Object plays a killer effect. This is done by putting the function into a separate object, and the temporary variable in the function becomes the field in the object.

Before impulse:

Class Bill {public double FinalPrice () {double primaryPrice; double secondaryPrice; double teriaryPrice; / / long computation...}}

After impulse:

Class Bill {public double FinalPrice () {return new PriceCalculator (this) .compute ();}} class PriceCalculator {double primaryPrice; double secondaryPrice; double teriaryPrice; public PriceCalculator (Bill bill) {/ / initial} public double compute () {/ / computation}}

9. Substitute Algorithm (replacement algorithm)

Explanation:

There is a joke:

In a multinational daily chemical company, the soap production line may leak soap during packaging, so the president of the company ordered an expert group led by a doctor to tackle the problem. The R & D team used the world's cutting-edge technologies (such as infrared detection, laser irradiation, etc.). After spending a lot of dollars and half a year, the soap box detection system is finally completed. after detecting the empty soap box, the manipulator will push the empty box out. This method effectively reduces the empty filling rate of soap boxes to less than 5%, and the problem is basically solved.

A township soap enterprise also encountered a similar problem. The boss ordered the assembly line foreman who graduated from junior high school to find a way to solve it. After a long day of thinking, the foreman took an electric fan to the end of the production line and blew hard at the conveyor belt. Those soap boxes without soap were blown down by the wind because of their light weight.

This joke can well explain Substitute Algorithm, for the complex algorithm in the function, try to simplify the algorithm, so as to achieve the same or even better results as before.

This is the end of the article on "what are the components of Java optimization functions?" Thank you for reading! I believe that everyone has a certain understanding of the knowledge of "what is the composition of the Java optimization function". If you want to learn more knowledge, you are welcome to follow the industry information channel.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report